我试图弄清楚猫鼬如何使用它的连接。目前我有:
// 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
});
我认为我以错误的方式处理这个问题......第一种方法是否可行,而我做错了什么?