4

我试图弄清楚猫鼬如何使用它的连接。目前我有:

// 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
});

我认为我以错误的方式处理这个问题......第一种方法是否可行,而我做错了什么?

4

2 回答 2

8

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

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

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

于 2012-08-21T13:33:15.320 回答
2

看看它说的文档:

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

也许您需要将您的连接详细信息放入创建连接

var mongoose = require('mongoose'),
conn = mongoose.createConnection('localhost', 'test');
于 2012-08-21T11:51:01.540 回答