[英]How do you delete a Json object by id in node Mongodb?
i have a Mongodb collection named "EVENTS" and in the collection i have an object of array which looks like this: 我有一个名为“ EVENTS”的Mongodb集合,并且在集合中有一个数组对象,如下所示:
{
"Events":[
{
"_id":"53ae59883d0e63aa77f7b5b2",
"Title":"Title Blank",
"Desc":"Description Blank",
"Date":"2014-06-04 00:30",
"Link":"http://googleparty.com",
"Event":"Victoria Centre",
"dateCreated":"28/6/2014 06:58"
},
{
"_id":"53ae59883d0e63aa77f7b5b3",
"Title":"Hello World",
"Desc":"hello",
"Date":"2014-06-04 00:30",
"Link":"http://linkedinparty.com",
"Event":"social",
"dateCreated":"30/2/2014 11:10"
}
]
}
how would i delete an object by id in node.js so " delete(53ae59883d0e63aa77f7b5b2)" will yield this: 我将如何通过node.js中的ID删除对象,因此“ delete(53ae59883d0e63aa77f7b5b2)”将产生以下内容:
{
"Events":[
{
"_id":"53ae59883d0e63aa77f7b5b3",
"Title":"Hello World",
"Desc":"hello",
"Date":"2014-06-04 00:30",
"Link":"http://linkedinparty.com",
"Event":"social",
"dateCreated":"30/2/2014 11:10"
}
]
}
Regards 问候
If all you really want to do is "empty" the array then you just need to use the $set
operator with an .update()
and "set" the array as an empty one: 如果您真正想做的只是“清空”数组,则只需将$set
运算符与.update()
一起使用,并将数组“设置”为空:
db.collection.update({},{ "$set": { "Events": [] } },{ "mutli": true})
So the .update()
operation takes a "query" to select the documents in your collection, a blank query as shown selects everything. 因此, .update()
操作使用“查询”来选择集合中的文档,如图所示的空白查询会选择所有内容。 The "update" section contains the $set
operation that just replaces the current "Events" field with an empty array. “更新”部分包含$set
操作,该操作仅将当前的“事件”字段替换为空数组。
The "multi" option there makes sure this is applied to every document that matches. 此处的“ multi”选项可确保将其应用于所有匹配的文档。 The default is false
and will only update the first document that matches. 默认值为false
,将仅更新匹配的第一个文档。
For more specific operations removing selected array elements, look at the $pull
operator. 有关删除选定数组元素的更具体的操作,请查看$pull
运算符。 Your edit shows now that this is what you want to do: 您的编辑现在显示出您要执行的操作:
db.collection.update(
{ "Events._id": ObjectId("53ae59883d0e63aa77f7b5b2") },
{ "$pull": { "Events": { "_id": ObjectId("53ae59883d0e63aa77f7b5b2") } } }
)
But your inclusion of arrays with _id
fields seems to indicate that you are using mongoose, so the ObjectId values are cast automatically: 但是,包含_id
字段的数组似乎表明您使用的是猫鼬,因此ObjectId值是自动转换的:
Model.update(
{ "Events._id": "53ae59883d0e63aa77f7b5b2" },
{ "$pull": { "Events": { "_id": "53ae59883d0e63aa77f7b5b2" } } },
function(err,numAffected) {
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.