2

我有一个架构设计这样猫鼬查询内部文件阵列

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); 
}); 

但这返回[]作为结果。

+0

什么是你的猫鼬版本在应用程序中使用? –

+0

猫鼬版本4.6.1 –

+0

查询看起来正确,用户ID是否正确_id? –

回答

1

您可以使用aggregate尝试,如果你想获得只具有isRead场的通知是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); 
}) 

例如您的文档,如:

{ 
    "_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); 
}) 
+0

我不明白为什么消极,你能告诉我吗? –