node.js - 如何删除一个没有集合名称的文档?
问题描述
我有一个模型,它有一个像这样的嵌套字段:
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 来删除字段数组中的对象。我怎样才能做到这一点?
解决方案
您可以在 mongodb 中使用$pull来执行此操作。
样本:
YourModel.updateMany({}, {$pull: {fields: {id: your_id}}})
或者如果你想删除一个 id 数组:
YourModel.updateMany({}, {$pull: {fields: {id: {$in: your_array_id}}}})
推荐阅读
- json - 使用 jsons 将 JSON 字符串反序列化为嵌套对象
- java - 需要帮助计算 MaxHeap 中的交换次数
- c# - 为什么ajax说在服务器上找不到404?
- c# - 无法在 c# 中为 EventArgs 分配使用派生类型的事件处理程序
- c# - Bitmap.Compress() 使用哪个流?
- html - 正则表达式匹配 HTML 和非 HTML URL
- algorithm - 用于生成此表中数字的算法是什么,N = 6 的输出是什么?
- css - 如何使用伪元素隐藏img标签
- c - 如何在 BST 中找到小于或等于给定值的节点数?(AVL 树)
- c - 比较函数在 qsort 中给出分段错误