【问题标题】:mongoose Querying inner document array猫鼬查询内部文档数组
【发布时间】:2017-01-03 18:44:27
【问题描述】:

我有这样的架构设计

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

但这会返回[] 作为结果。

【问题讨论】:

  • 您的应用中使用的猫鼬版本是什么?
  • 猫鼬版本 4.6.1
  • 查询看起来正确,_id 的用户 ID 是否正确?
  • 您是否尝试过仅使用isRead 属性进行查询,例如Model.User.find({ "notification.isRead": false }).exec(callback)?你有任何结果吗?如果是这样,则检查仅包含userid 的查询是否有效,即Model.User.find({ "_id": userid }).exec(callback)。如果这没有给您任何结果,则表示您指定的 userid 不存在,这可能是组合过滤器不起作用的原因。

标签: node.js mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

如果您只想获取具有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 是错误的。也可以使用$elemMatch

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

【讨论】:

  • 我不明白为什么是负面的,你能告诉我吗?
【解决方案2】:

我猜你的参考是错误的,因为查询是正确的。

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

例子:

如果您在架构代码中引用 notifications,那么您应该在代码中导出相同的名称。

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

看这里https://alexanderzeitler.com/articles/mongoose-referencing-schema-in-properties-and-arrays/

【讨论】:

    猜你喜欢
    • 2015-06-26
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2019-10-19
    • 2014-03-21
    • 1970-01-01
    • 2013-10-21
    • 2022-01-17
    相关资源
    最近更新 更多