I'm trying to get mongoose populate to work.
I have two models one for orders and the other for the order items.
I'm doing this purely to understand populate.
I did have two files for this but I have now got everything in one file called main.js
main.js creates the 3 items in items model.
I then try to populate the order model with the 3 items.
Output for the query now gives the correct populated result.
That is to say the output from the line
console.log(JSON.stringify(orders, null, "\t");
is now:
[ { "_id": "55d32e4594db780b1bbb4372", "__v": 0, "lines": [ { "price": 2.4, "quantity": 5, "_id": "55d32e4594db780b1bbb436f", "__v": 0 }, { "price": 3.7, "quantity": 7, "_id": "55d32e4594db780b1bbb4370", "__v": 0 }, { "price": 1.2, "quantity": 3, "_id": "55d32e4594db780b1bbb4371", "__v": 0 } ] } ]
The database however is not populating.
Below is the main.js file
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb');
var Schema = mongoose.Schema;
var OrderSchema = new Schema({
lines: [{type: mongoose.Schema.Types.ObjectId, ref: 'Item'}]
});
var ItemSchema = new Schema({
price: Number,
quantity: Number
});
var Order = mongoose.model('Order', OrderSchema);
var Item = mongoose.model('Item', ItemSchema);
var itemArray = [
{price: 2.4, quantity: 5},
{price: 3.7, quantity: 7},
{price: 1.2, quantity: 3}
];
Item.create(itemArray, function(err) {
if (err) {
console.log('Error creating items: ', err);
}
var order = new Order();
Item.find({}, {_id: 1}, function(err, result) {
result.forEach(function(obj) {
order.lines.push(obj._id);
});
}).exec().then(function() {
order.save(function(err) {
if (!err) {
Order.find({})
.populate('lines')
.exec(function(err, orders) {
console.log(JSON.stringify(orders, null, "\t")); // output is populated the database is still not populating.
});
}
});
} );
});
.populate()call just pulls in the already attached item data as first class objects and not references. You seem to be expecting that it is just going to somehow "magically" add the items in. - Blakes Sevenpopulate()does not add items to your object. There are pretty clear examples in the mongoose documentation. - Blakes Seven