猫鼬和模型连接

时间:2012-08-21 11:27:07

标签: 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 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
});

我认为我正以错误的方式接近这个......如果第一种方法有效,我做错了吗?

2 个答案:

答案 0 :(得分:8)

最简单的方法是打开所有mongoose调用共享的默认连接池:

// Datastore.js
var mongoose = require('mongoose'),
    db = mongoose.connect('localhost', 'dbname');

然后在所有其他文件中使用mongoose.model(...)访问池。

答案 1 :(得分:2)

docs它说:

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

也许您需要将连接详细信息放入create Connection

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