首页 > 解决方案 > 如何删除一个没有集合名称的文档?

问题描述

我有一个模型,它有一个像这样的嵌套字段:

 static getSchema (){
        return {
            document_template: {
                type: Mongoose.Schema.Types.ObjectId,
                ref: TEMPLATE_MODEL_NAME
            },

            department: {
                type: Mongoose.Schema.Types.ObjectId,
                ref: DEPARTMENT_MODEL_NAME
            },

            fields: {
                type: [ new Mongoose.Schema({
                    key: {
                        type: String,
                        required: true,
                        trim: true
                    },
                    value: {
                        type: Object,
                        required: true,
                    }
                }) ],
                required: false
            }
        };
    } /* getSchema() */

如您所见,“fields”字段包含一个对象数组。因为我为数组中的对象定义了一个新模式,所以该数组中的每个对象都有一个“_id”字段。但是数据库中没有这些对象的集合名称。如何删除这些没有任何集合名称但有 _id 的文档?

下面是一个文档示例:

{
                "id": "5d232d9ed64d4ea7bdd1cac5",
                "template_id": "5d1df82b9bbf985a5aaac50e",
                "department": "5d1dc4d9c7c4504fef430eec",
                "fields": [
                    {
                        "id": "5d29967eb60ca9f88d97451b",
                        "key": "field 3",
                        "value": "333"
                    },
                    {
                        "id": "5d29967eb60ca9f88d97451a",
                        "key": "field 2",
                        "value": "asde"
                    }
                ]
}

我想只使用它们的 id 来删除字段数组中的对象。我怎样才能做到这一点?

标签: node.jsmongodbmongoose

解决方案


您可以在 mongodb 中使用$pull来执行此操作。

样本:

YourModel.updateMany({}, {$pull: {fields: {id: your_id}}})

或者如果你想删除一个 id 数组:

YourModel.updateMany({}, {$pull: {fields: {id: {$in: your_array_id}}}})

推荐阅读