1

我目前有 3 个 MongoDB 数据库,我使用mongoose.createConnection(...). 对于每个数据库,我为数据库中的所有集合定义模式和模型。我遇到的问题是,当我查询一个集合时,返回的结果没有任何属性集。但是,使用node-inspector,我可以看到属性已从 db 正确加载,因为它们存在于_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。

4

0 回答 0