【问题标题】:Unhandled Rejection (TypeError): mongoose.connect is not a function未处理的拒绝(TypeError):mongoose.connect 不是函数
【发布时间】:2021-04-23 07:31:09
【问题描述】:

我尝试了许多不同的更改,但似乎没有任何效果。我试过切换到导入语句。我试过将代码放在 App.js 中。我试过使用 mongodb 库而不是 mongoose。我已经学习了十几个关于连接到 mongodb 的教程。出于某种原因,connect 语句不断抛出此错误。我错过了什么?

const mongoose = require('mongoose');

export async function post({username, password}) {
  const data = {username, password};
  const uri =
    'mongodb+srv://[username removed]:[password removed]@[project name removed].krcm7.mongodb.net/database?retryWrites=true&w=majority';
  mongoose
    .connect(uri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then((result) => console.log('connected to db'))
    .catch((err) => console.log(err));

  return;
}

要添加上下文,这是调用函数的方式。

function submitForm(username, password) {
  post(username, password).then(() => {
    console.log('post function ran');
  });
}

【问题讨论】:

  • 除了奇怪的缩进之外,我看起来很好,但我确信这是有效的。这个错误不应该发生 - 如果你 console.log(mongoose),你会得到什么,你有什么版本的 npm、node 和 mongoose?
  • 你的收获是什么? console.log(err)
  • catch 没有运行,因为错误发生在第 7 行(猫鼬)。我正在运行 yarn v1.22.10、node v14.15.0 和 mongoose v^5.12.5
  • 试过回溯猫鼬,但仍然有错误。

标签: node.js mongodb react-native mongoose react-native-web


【解决方案1】:

我发现了问题。 Mongodb 和 mongoose 专为在 node.js 中工作而设计,不能在浏览器环境中工作。

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 2021-10-14
    • 2020-11-16
    • 2020-05-06
    • 2019-10-27
    • 2020-09-26
    • 2021-04-16
    • 2021-03-09
    • 1970-01-01
    相关资源
    最近更新 更多