gpt4 book ai didi

node.js - 如何使用 MongoDB 删除对象内部的对象(不在数组内部)

转载 作者:可可西里 更新时间:2023-11-01 09:11:32 24 4
gpt4 key购买 nike

<分区>

假设我有这个结构:

{
"_id" : ObjectId("52af7c1497bcaf410e000002"),
"created_at" : ISODate("2013-12-16T22:17:56.219Z"),
"name" : "Hot",
"subcategories" : {
"Loco" : {
"subcategory" : "Loco",
"id" : "522423de-fffe-44be-ed3b-93fdd50fdb4f",
"products" : [ ]
},
"Loco2" : {
"subcategory" : "Loco2",
"id" : "522423de-fffe-44be-ed3b-93fdd50fd55",
"products" : [ ]
},
}
}

我怎样才能从子类别中删除 Loco2 而保留其他所有内容?

请注意,我的对象选择器是 ObjectId,因为其他文档的结构可能具有属于不同文档的相同子类别名称。例如,我还可以有另一个像这样的对象:

{
"_id" : ObjectId("52af7c1497bcaf410e000003"),
"created_at" : ISODate("2013-12-16T22:17:56.219Z"),
"name" : "Medium",
"subcategories" : {
"Loco" : {
"subcategory" : "Loco",
"id" : "522423de-fffe-44be-ed3b-93fdd50332b4f",
"products" : [ ]
},
"Loco2" : {
"subcategory" : "Loco2",
"id" : "522423de-fffe-44be-ed3b-93fdd522d55",
"products" : [ ]
},
}
}

所以我的查询应该是这样的:db.categories.update({"_id": "ObjectId("52af7c1497bcaf410e000003")"}, {还不知道这部分})

编辑:当我知道要删除的子类别的名称时,答案确实在 shell 上起作用,但是我无法让它在我的 Node 应用程序中起作用:

    Categories.prototype.delSubcategory = function(categoryId, subcategory, callback) {

this.getCollection(function(error, category_collection) {

if(error) callback(error);

else {

category_collection.update(

{_id: category_collection.db.bson_deserializer.ObjectID.createFromHexString(categoryId)},
{ $unset : { "subcategories.Loco2: "" } },
function(error, subcategory) {

if(error) callback(error);

else callback(null, subcategory)

}

)

}

});

};

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com