[英]Update/Insert an element in a nested stringified array of a mongoDB document
我的收藏具有以下結構:
{
"_id" : "7ZEc8dkbs4tLwhW24",
"title" : "title",
"json" :
{
\"cells\":[
{
\"type\":\"model\",
\"size\":{\"width\":100,\"height\":40},
\"id\":\"11dc3b6f-2f61-473c-90d7-08f16e7d277a\",
\"attrs\":{
\"text\":{\"text\":\"content\"},
\"a\":{\"xlink:href\":\"http://website.com\",\"xlink:show\":\"replace\",\"cursor\":\"pointer\"}
}
}
]
}
}
現在,我需要在流星應用程序中插入/更新字段json.cells.attrs.a
。 我得到的所有信息都是_id
(文檔ID)和id
(單元格中元素的ID)。 如果a
不存在,則應創建該元素。
我的嘗試是不正確的,因為查詢不是在尋找elemID來獲取cells-array中的正確元素:
var linkObject = {"xlink:href":"http://newURL.com","xlink:show":"replace","cursor":"pointer"};
var docID = '7ZEc8dkbs4tLwhW24';
var elemID = '11dc3b6f-2f61-473c-90d7-08f16e7d277a'; // How to search for this 'id'?
var result = Collection.findOne({ _id: docID });
var json = JSON.parse(result.json);
// find id = elemID in 'json'
// add/update 'a'
// update json in mongoDB document
在您的代碼中,您僅將docID
作為條件添加到查詢中。 您必須將elemID
添加到查詢條件中。 然后,您可以使用dot.notation
和$(Positional Operator)
更新attrs
對象的a
屬性。 您可以這樣做:
Collection.update(
{"_id" : docID , "json.cells.id" : elemID },
{$set: { "json.cells.$.attrs.a" : linkObject}}
}
$set
,如果該字段不存在,將創建該字段。 如果您不知道數組位置,則可以使用$ Positional Operator
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.