Node.js 猫鼬与模型连接
我想弄清楚猫鼬是如何利用它的连接的。目前我有:Node.js 猫鼬与模型连接,node.js,mongoose,Node.js,Mongoose,我想弄清楚猫鼬是如何利用它的连接的。目前我有: // Datastore.js var mongoose = require('mongoose'), conn = mongoose.createConnection(); ... conn.open(host, database, port, options, callback); // Opens connection // Model.js var mongoose = require('mongoose'); var Sc
// Datastore.js
var mongoose = require('mongoose'),
conn = mongoose.createConnection();
...
conn.open(host, database, port, options, callback); // Opens connection
// Model.js
var mongoose = require('mongoose');
var Schema = new mongoose.Schema({...})
module.exports = exports = mongoose.model('MyModel', Schema);
// Controller.js
var mongoose = require('mongoose');
var MyModel = mongoose.model('MyModel'); // Retrieves the model ok
MyModel.find({}, function(err, docs){
if(err){} //
console.log(docs); // Does not work
});
但是这不起作用。。。只有在我以某种方式将连接传递给其他人时,它才会起作用,如下所示:
// Datastore.js
var mongoose = require('mongoose'),
conn = mongoose.createConnection();
...
conn.open(host, database, port, options, callback); //
mongoose.set('db', conn);
// Controller.js
var mongoose = require('mongoose'),
db = mongoose.get('db');
var MyModel = db.model('MyModel'); // Retrieve the model using the connection instance
MyModel.find({}, function(err, docs){
if(err){} //
console.log(docs); // Works
});
我想我用错误的方式来处理这件事。。。第一种方法有效吗?我做错了什么吗?看看它说:
也许您需要为创建连接输入连接详细信息
var mongoose = require('mongoose'),
conn = mongoose.createConnection('localhost', 'test');
打开所有mongoose调用共享的默认连接池是最简单的:
// Datastore.js
var mongoose = require('mongoose'),
db = mongoose.connect('localhost', 'dbname');
然后在所有其他文件中使用
mongoose.model(…)
访问池连接部分正常,我已成功连接。使用“打开”只会延迟连接发生的时间。谢谢-我如何设置默认连接?这就是mongoose.connect
调用所做的。我添加了典型参数。谢谢-我不确定这与我使用的方法之间的区别,以及为什么这两种技术在访问连接的模型中不同。@leepowell如果您使用原始方法,您需要到处传递conn
,并调用conn.model
而不是mongoose.model
。如果您在多个位置使用您的模型,这将不再有效。
// Datastore.js
var mongoose = require('mongoose'),
db = mongoose.connect('localhost', 'dbname');