I am trying to populate two tables in mongoose and node and I receive the error that populate is not a function.
I have search and in the documentation it seems that it does the same as I.
Here the model:
var mongoose = require('mongoose');
var dodleSchema = new mongoose.Schema({
name: String,
productorId: {type: mongoose.Schema.ObjectId, ref: "Productor"},
description: String,
ambassadorId: {type: mongoose.Schema.ObjectId, ref: "Ambassador"},
accepted: { type: Boolean, default: false },
read: { type: Boolean, default: false },
deliveryAddress: {
lat: String,
lng: String
},
createdAt: Date,
products: [
{
primaryImage: String,
images: [],
name: String,
max: Number,
min: Number,
step: Number,
stock: Number,
normalPrice: Number,
doodlePrice: Number,
freeShipping: Boolean,
freeShippingFrom: Number
}
],
endsAt: Date,
packagingType: String,
orders: [
{
name: String,
email: String,
purchases: [
{
productId: String,
quantity: Number
}
]
}
]
});
module.exports = mongoose.model('Doodle', dodleSchema);
And then the find that I use:
router.route('/requests/:id')
.get(function (req, res) {
doodleCollection
.find({
ambassadorId: new mongodb.ObjectID(req.params.id),
read: false
})
.populate('productorId')
.toArray(function (error, results) {
if (error) {
res.json({'error': "Ha habido un error en la extracción de requests"});
return false;
}
var alertNew = false;
for (var i = 0; i < results.length; i++) {
if (results[i].read == false) {
readed = true;
break;
}
}
res.json({
requests: results,
alertNew: alertNew
});
});
});
This is the error that I get:
I found the solution and was pretty easy. Seemed that I was really close yesterday.
I was doing the populate method in a collection doodleCollection
and I needed to do it in the model.
Changing the object that makes the find totally worked.
Instead of doodleCollection.find(...)
now I call doodleModel.find(...)
and populate is working perfect!