mongoose查询内部文件数组
我有这样的模式devise
var userNotificationSchema = new Schema({ notification_id: { type: Schema.Types.ObjectId, ref: 'notifications' }, isRead: { type: Boolean } }); var userSchema = new Schema({ notification: [userNotificationSchema] });
我想获取所有的通知数组列表,这是isRead: 'false'
。
为此我写了
Model.User.find({ _id: userid, 'notification.isRead': false }, function (err, result) { console.log(result); res.send(result); });
但是这返回结果[]
。
如果只想获取具有isRead
字段的通知,则可以使用aggregate
来尝试。
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); })
比如你的文档就像:
{ "_id" : ObjectId("58454926668bde730a460e15"), "notification" : [ { "notification_id" : ObjectId("58454926668bde730a460e16"), "isRead" : true }, { "notification_id" : ObjectId("58454926668bde730a460e17"), "isRead" : true }, { "notification_id" : ObjectId("58454926668bde730a460e19"), "isRead" : false } ] }
那么输出将会是这样的:
{ "_id" : ObjectId("58454926668bde730a460e15"), "notification" : [ { "notification_id" : ObjectId("58454926668bde730a460e19"), "isReady" : false } ] }
如果你想得到所有的通知,如果任何一个isRead
为false
那么你的查询是正确的,只是检查userid
是否存在于你传递的数据库中,并且一些通知isRead
是假的。 也可以使用$elemMatch
Model.User.find({ _id: userid "notification":{ $elemMatch: { "isRead": false} } }).exec(function (err, result) { console.log(result); res.send(result); })
我的猜测是你的参考是错误的,因为查询是正确的。
确保你指的是你的出口。
例:
如果您在架构代码中引用notifications
,那么您应该在代码中导出相同的名称。
module.exports = mongoose.model("notifications", userNotificationSchema);
看看这里https://alexanderzeitler.com/articles/mongoose-referencing-schema-in-properties-and-arrays/