【发布时间】: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()返回什么?您是否阅读了已经解释过的文档?