Node.js mongoose查询内部文档数组

Node.js mongoose查询内部文档数组,node.js,mongodb,mongoose,mongodb-query,aggregation-framework,Node.js,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我有一个这样的模式设计 var userNotificationSchema = new Schema({ notification_id: { type: Schema.Types.ObjectId, ref: 'notifications' }, isRead: { type: Boolean } }); var userSchema = new Schema({ notification: [userNotificationSchema] }); 我想获取

我有一个这样的模式设计

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

但是这将返回结果
[]

我猜您的引用是错误的,因为查询是正确的

确保您引用的是您要导出的内容

例如:

如果您在模式代码中引用的是
通知
,则应在代码中导出相同的名称

module.exports = mongoose.model("notifications", userNotificationSchema);

查看此处

如果您只想获取那些具有
isRead
字段为
false
的通知,可以使用
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
为false即可。也可以使用
$elemMatch

Model.User.find({
   _id: userid
   "notification":{ $elemMatch: { "isRead": false} }
}).exec(function (err, result) {
  console.log(result);
  res.send(result);
})

你在应用程序中使用的mongoose版本是什么?mongoose版本4.6.1query看起来正确,userid对于_id正确吗?你是否尝试过只使用
isRead
属性进行查询,如
Model.User.find({“notification.isRead”:false})。exec(回调)
?你有什么结果吗?如果是,则检查仅使用
userid
的查询是否有效,即
Model.User.find({“\u id”:userid}).exec(回调)
。如果这没有给你任何结果,那就意味着你指定的
userid
不存在,这可能是组合过滤器无法工作的原因。我不明白为什么是否定的,你能告诉我吗?