I currently have 3 MongoDB databases to which I connect from a Node.js app using mongoose.createConnection(...). For each db, I define schemas and models for all collections in the db. The problem I have is that when I query a collection, the results returned do not have any attributes set. However, using node-inspector, I can see that the attributes are loaded correctly from the db because they are present in the _doc attribute.
Example (some code is omitted):
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'
});
});
The question is, am I forgetting to do something when I connect? I have also tried to specify the attributes to fetch using populate after calling find, but with no success.
I am using MongoDB 2.4.3, Node.js 0.10.6 and Mongoose 3.6.11.