I have a schema design like this
var userNotificationSchema = new Schema({
notification_id: { type: Schema.Types.ObjectId, ref: 'notifications' },
isRead: { type: Boolean }
});
var userSchema = new Schema({
notification: [userNotificationSchema]
});
I want to fetch all notifications array list which isRead: 'false'.
For that I wrote
Model.User.find({
_id: userid,
'notification.isRead': false
}, function (err, result) {
console.log(result);
res.send(result);
});
but this returns [] as result.
you can try it using aggregate if you want to get only those notifications that has isRead field is false.
Model.User.aggregate([
{$match:{_id: userid}},
{$unwind:"$notification"},
{$match:{"notification.isRead": false}},
{$group:{_id:"$_id",notification:{ $addToSet: "$notification"}}}
]).exec(function (err, result) {
console.log(result);
res.send(result);
})
For example your document like:
{
"_id" : ObjectId("58454926668bde730a460e15"),
"notification" : [
{
"notification_id" : ObjectId("58454926668bde730a460e16"),
"isRead" : true
},
{
"notification_id" : ObjectId("58454926668bde730a460e17"),
"isRead" : true
},
{
"notification_id" : ObjectId("58454926668bde730a460e19"),
"isRead" : false
}
]
}
then out put will be like:
{
"_id" : ObjectId("58454926668bde730a460e15"),
"notification" : [
{
"notification_id" : ObjectId("58454926668bde730a460e19"),
"isReady" : false
}
]
}
If you want to get all notifications if any one of isRead is false then your query is correct just check userid is is exist in DB that you passed and some notification isRead is false . Also can use $elemMatch
Model.User.find({
_id: userid
"notification":{ $elemMatch: { "isRead": false} }
}).exec(function (err, result) {
console.log(result);
res.send(result);
})
My guess is your reference is wrong because the query is correct.
Make sure you are referring what you exporting.
Example:
If you are referring notifications in your schema code then you should export the same name in code.
module.exports = mongoose.model("notifications", userNotificationSchema);
Take a look at here https://alexanderzeitler.com/articles/mongoose-referencing-schema-in-properties-and-arrays/