【问题标题】:Can't understand the connect in mongoose无法理解猫鼬中的连接
【发布时间】:2018-08-22 15:21:44
【问题描述】:

我在nodejs中使用mongoose连接mongodb

const mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/testdb", {useNewUrlParser: true});
let db = mongoose.connection;
db.on("error", function (error) {
    console.log("fail--->" + error);
});
db.on("open", function () {
    console.log("connected");
});

这很好,我找到了另一种方法,并将上面的代码更改为

const mongoose = require("mongoose");
let db = mongoose.connect("mongodb://127.0.0.1:27017/testdb", { useNewUrlParser: true });
db.connection.on("error", function (error) {
    console.log("fail--->" + error);
});
db.connection.on("open", function () {
    console.log("connected");
});

但这会引发错误

db.connection.on("error", function (error) {
          ^
TypeError: Cannot read property 'on' of undefined

谁能帮我解释一下?以上两段代码有什么不同,非常感谢。

【问题讨论】:

  • 您希望.connect() 返回什么?您是否阅读了已经解释过的文档?

标签: node.js mongodb mongoose


【解决方案1】:

mongoose.connect() 只建立一个到数据库的连接并返回一个承诺。 Mongoose 在您调用mongoose.connect() 时创建默认数据库连接,您可以使用mongoose.connection 访问此默认连接。现在您可以使用错误/打开等事件检查此连接的状态。

您的第二段代码不起作用,因为mongoose.connect() 返回承诺而不是数据库连接对象。您正在尝试访问不存在的 connection 属性,因此抛出错误未定义属性错误。

db.connection.on("error", function (error) {
          ^
TypeError: Cannot read property 'on' of undefined

希望对你有帮助:)

.

【讨论】:

  • 我在一小时前找到了,但还是谢谢你。
猜你喜欢
  • 2022-12-11
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多