gpt4 book ai didi

node.js - mongoose.connection() 和 mongoose.createConnection() 之间的混淆

转载 作者:IT老高 更新时间:2023-10-28 23:26:59 24 4
gpt4 key购买 nike

我已经研究了 mongoose 三天了,对这两种方法的使用有点困惑(我知道“mongoose.connection()”将来会被弃用......)

问题是:当我试图转换(从“mongoose.connection()”到“mongoose.createConnection()”)这个例子的action.js文件https://gist.github.com/2785463它似乎不适合我...

这是我的代码...

var mongoose = require('mongoose'),
db = mongoose.createConnection('localhost', 'test');

db.on('error', function () {
console.log('Error! Database connection failed.');
});

db.once('open', function (argument) {
console.log('Database connection established!');

mongoose.connection.db.collectionNames(function (error, names) {
if (error) {
console.log('Error: '+ error);
} else {
console.log(names);
};
});
});

还有我的终端输出(在我的 ubuntu 终端上键入“node test.js”..)

Database connection established!

/home/_user_/Scrivania/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:437
throw err;
^
TypeError: Cannot call method 'collectionNames' of undefined
at NativeConnection.<anonymous> (/home/_user_/Scrivania/test2.js:11:25)
at NativeConnection.g (events.js:192:14)
at NativeConnection.EventEmitter.emit (events.js:93:17)
at open (/home/_user_/Scrivania/node_modules/mongoose/lib/connection.js:408:10)
at NativeConnection.Connection.onOpen (/home/_user_/Scrivania/node_modules/mongoose/lib/connection.js:415:5)
at Connection._open (/home/_user_/Scrivania/node_modules/mongoose/lib/connection.js:386:10)
at NativeConnection.doOpen (/home/_user_/Scrivania/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:47:5)
at Db.open (/home/_user_/Scrivania/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:287:14)
at Server.connect.connectCallback (/home/_user_/Scrivania/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:235:7)
at g (events.js:192:14)

最佳答案

如果你不调用 mongoose.connect() 那么 mongoose.connection 不包含一个打开的连接。您应该改用 mongo.createConnection() 调用的返回值(您已保存到 db 中)。

所以最后一段代码应该改为:

更新

db.db.collectionNames(function (error, names) {
if (error) {
console.log('Error: '+ error);
} else {
console.log(names);
};
});

我在 Connection 上没有看到 collectionNames 方法;看起来您必须将属性向下跟踪到 native 连接对象才能访问它(参见上面的代码)。

关于node.js - mongoose.connection() 和 mongoose.createConnection() 之间的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13162979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com