Reputation: 4448
I am new to mongodb, using Mean stack from meanjs.org.
I have a model with a user collection relationship:
var MealSchema = new Schema({
mealDate: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Meal', MealSchema);
I had find an implementation that works:
var user = req.user;
Meal.find({
mealDate: {
$gte: minus8days.toDate(),
$lt: tomorrow.toDate()
},
user : user
}).exec(function (err, meals) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(meals);
}
});
But I need some grouping and aggregation so I am trying to change this code to use aggregate instead of a find, I've tried many combinations and I keep getting an error, basically the following implementation throws an error MongoError: Maximum call stack size exceeded
Meal.aggregate([
{
$match: {
$and: [
{
mealDate: {
$gte: minus8days.toDate(),
$lt: tomorrow.toDate()
}
}, { user: user }
]
}
}]...
Why user:user works with find and not with aggregate? How can the aggregate approach be fixed?
Upvotes: 0
Views: 114
Reputation: 39442
Try this :
Meal.aggregate([
{
$match: {
mealDate: { $gte: minus8days.toDate(), $lt: tomorrow.toDate()},
user: user._id
}
}
], function(err, docs){
if(err) console.log("Error : " + JSON.stringify(err));
if(docs) console.log("Got the docs successfully : " + JSON.stringify(docs));
});
Upvotes: 1