mongoose.connect 不是函数 - React Native

mongoose.connect is not a function - React Native

在弄乱我的 passport 会话并与它们一起实现 JWT 之后,我尝试了 运行 我的应用程序,但遇到了一些我无法解决的错误:

ERROR TypeError: mongoose.connect is not a function. (In 'mongoose.connect(config.MongoURL, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false })', 'mongoose.connect' is undefined)

ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

让我有点困惑的是与我的mongodb的连接实际上是成功的,因为我能够console.log(data)在承诺中在 mongoose.connect() 函数之后,没有任何错误被捕获。我还尝试访问我的服务器端(使用 Postman)并执行一些使用我的数据库的 Get 和 Post 函数,请求也成功完成!

至于其他两个错误,我不知道它们是什么意思。

这是我的 db/index.js 以防万一:

const mongoose = require('mongoose');
const config = require('../config/index');

mongoose.Promise = global.Promise;
mongoose
  .connect(config.MongoURL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
  })
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.error(err);
  });

const db = mongoose.connection;
db.on('error', (err) => {
  console.log(`There was an error connecting to the database: ${err}`);
});
db.once('open', () => {
  console.log('connected');
});

module.exports = db;

这是处理通用代码时的常见问题:有些部分可能无法在浏览器中运行,有些则无法在 Node.js 中运行。有时它很好,因为它简化了关注点的分离,有时则不然,因为您实际上希望在这些域之间共享一些关注点。但有时 - 这是最坏的情况 - 它在不应该共享的时候共享。

这个特殊案例之所以有趣,有两个原因。

首先,正如您提到的,您的构建尝试从 db 导入一些 client-side 代码的依赖项。那不行,因为一般来说,server-side DB 不应直接在客户端上使用。是的,db/index.js 不仅定义了要导出的函数和类型,而且实际上还有一些 'executable' 语句。比较一下:

export default function someFunction() {
  // this is not invoked on import - only when `someFunction` is called!
  require('mongoose').connect('...');
}

...使用您现在拥有的代码。

其次,如链接问题中所述,require('mongoose') 不会失败,因为它实际上可以用于双方。尽管如此,下一个 executable 语句确实失败了,因为“客户端”猫鼬没有 connect 方法。

对于那些仍然对实际导致错误的原因感到困惑的人,这是我 client-side 屏幕之一开头的 import { states } from '../../server/db';。删除它后应用程序构建成功。

请参阅已接受的答案以更好地理解为什么会导致错误。