【问题标题】:Querying nested objects using find not working in mongoose (MongoDB)使用 find 在 mongoose (MongoDB) 中不起作用查询嵌套对象
【发布时间】:2021-11-12 09:43:55
【问题描述】:

我正在尝试获取具有 isDrafttrue 的对象,但我也在获取具有 isDraftfalse 的对象。我只需要具有 isDrafttrue 的对象。我已经尝试了所有可能的方法,但无法找到解决方案。谁能帮我解决这个问题?

下面是架构、查询和响应。

架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Contract = new Schema({
    name: {
        type: String,
        unqiue: true,
        required: true
    },
    version: [
        {
            no: {
                type: Number,
                required: true
            },
            sections: [
                {
                    sectionName: {
                        type: String,
                        required: true
                    },
                    clause: [{
                        description: {
                            type: String,
                            required: true
                        },
                    }]
                }
            ],
            approvedBy: [
                {
                    user: {
                        type: Schema.Types.ObjectId,
                        ref: 'user'
                    },
                }
            ],
            acceptedBy: [
                {
                    name: {
                        type: String,
                    },
                    eamil: {
                        type: String,
                    },
                }
            ],
            isDraft: {
                type: Boolean,
                required: true
            },
            date: {
                type: Date,
                default: Date.now
            }
        }
    ],
    createdBy: {
        type: Schema.Types.ObjectId,
        ref: 'user',
        required: true
    },

});

module.exports = mongoose.model('contract', Contract);

查询

query = {
            $and: [
                { createdBy: clientAdminDetails._id },
                { "version.isDraft": true }
            ],
        };
        await Contract
            .find(query)
            .skip(req.body.noOfItems * (req.body.pageNumber - 1))
            .limit(req.body.noOfItems)
            .exec((err, contract) => {
                if (err) {
                    return res.json(err);
                }
                Contract.countDocuments(query).exec((count_error, count) => {
                    if (err) {
                        return res.json(count_error);
                    }
                    return res.json({
                        total: count,
                        page: req.body.pageNumber,
                        pageSize: contract.length,
                        contracts: contract
                    });
                });
            });

回应

{
    "total": 1,
    "page": 1,
    "pageSize": 1,
    "contracts": [
        {
            "_id": "61449469775..",
            "name": "Octavia Blankenship",
            "version": [
                {
                    "_id": "614496593cc..",
                    "sections": [
                        {
                            "_id": "61449469775..",
                            "sectionName": "Est dolore dolorem n Updated `1323",
                            "clause": [
                                {
                                    "_id": "614494697..",
                                    "description": "Numquam nostrud et a"
                                }
                            ]
                        }
                    ],
                    "isDraft": false,
                    "no": 1,
                    "approvedBy": [],
                    "acceptedBy": [],
                    "date": "2021-09-17T13:21:29.509Z"
                },
                {
                    "_id": "614496122904ee4e046fbee8",
                    "sections": [
                        {
                            "_id": "6144955a8c0061025499606f",
                            "sectionName": "Praesentium suscipit",
                            "clause": [
                                {
                                    "_id": "6144955a8c00610254996070",
                                    "description": "Velit aperiam ut vel"
                                }
                            ]
                        }
                    ],
                    "isDraft": true,
                    "no": 2,
                    "approvedBy": [],
                    "acceptedBy": [],
                    "date": "2021-09-17T13:20:18.128Z"
                }
            ],
            "createdBy": "614367e980b29e6c...",
            "__v": 0
        }
    ]
}

【问题讨论】:

    标签: node.js express mongoose mongoose-schema


    【解决方案1】:

    这就是为什么使用您的查询告诉 mongo“给我一个文档,其中 createdBy 是所需的 id 并且 version.isdraft 是真实的”因此,由于文档包含这两个值,因此返回,即使是现有的 false数组。

    要解决这个问题,你有很多方法。

    第一个是使用$elemMatch 进行投影(docs here)。但是使用这种方式只会返回第一个元素,所以我认为您更喜欢其他方式。

    因此您可以像这样使用$filter 进行聚合查询:

    • 第一个 $match 按您想要的值(如您的查询)。
    • 然后通过 isDraft = true 的值覆盖 version 数组过滤。
    db.collection.aggregate([
      {
        "$match": {
          "createdBy": "",
          "version.isDraft": true
        }
      },
      {
        "$set": {
          "version": {
            "$filter": {
              "input": "$version",
              "as": "v",
              "cond": {
                "$eq": [
                  "$$v.isDraft",
                  true
                ]
              }
            }
          }
        }
      }
    ])
    

    例如here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-10
      • 2020-03-14
      • 2021-04-26
      • 2012-10-17
      • 2013-06-03
      • 2017-06-26
      • 2018-07-14
      • 2011-03-21
      相关资源
      最近更新 更多