我目前有3个MongoDB数据库,我使用mongoose.createConnection(...)
从Node.js应用程序连接到该数据库。对于每个db,我为db中的所有集合定义模式和模型。我遇到的问题是,当我查询集合时,返回的结果没有设置任何属性。但是,使用node-inspector
,我可以看到属性是从数据库中正确加载的,因为它们存在于_doc
属性中。
示例(省略了一些代码):
var mongoose = require('mongoose');
// Connect to a db
var db = mongoose.createConnection();
var options = { auto_reconnect: true };
db.open(args.host, args.db, args.port, options, function(error, connection) {
var buildModel = require('../models/' + dbName + '/schema.js');
buildModel(db);
}
// Define schemas and models (in schema.js). This is the `buildModel` function from above.
module.exports = function(mongoose) {
var Group = new Schema({
name: { type: String, required: true },
companyId: { type: ObjectId, required: true }
});
mongoose.model("Group", Group, 'groups');
};
// Querying
var Group = getDb('db1').model('Group');
Group.find({}, function(error, groups) {
// Here I get all documents in the groups collection, but the attributes
// name and companyId are not set.
groups.forEach(function(group) {
// name and companyId are undefined
console.log('undefined' == typeof group.name); // true
console.log('undefined' == typeof group.companyId); // true
// _doc attribute is populated
console.log(group._doc.name); // 'Group 1'
});
});
问题是,当我连接时,我忘了做某事吗?我还尝试在调用populate
后使用find
指定要获取的属性,但没有成功。
我使用的是MongoDB 2.4.3,Node.js 0.10.6和Mongoose 3.6.11。