0
所以我發現相當一些相關的SO如何在一個子陣列更新領域的職位,像這樣的一個here流星/蒙戈 - 子陣列添加/更新元素動態
我想達到什麼基本上是一樣的事情,但動態地更新子數組中的字段,而不是僅僅在查詢中調用字段名稱。 現在我還發現如何在主對象中直接做到這一點,但似乎無法在子數組中執行此操作。
代碼到子對象動態插入:
_.each(data.data, function(val, key) {
var obj = {};
obj['general.'+key] = val;
insert = 0 || (Documents.update(
{ _id: data._id },
{ $set: obj}
));
});
這裏是我試圖做樹:
Documents: {
_id: '123123'
...
smallRoom:
[
_id: '456456'
name: 'name1'
description: 'description1'
],
[
...
]
}
這裏是我的代碼:
// insert a new object in smallRoom, with only the _id so far
var newID = new Mongo.ObjectID;
var createId = {_id: newID._str};
Documents.update({_id: data._id},{$push:{smallRooms: createId}})
並插入其他字段的部分:
_.each(data.data, function(val, key) {
var obj = {};
obj['simpleRoom.$'+key] = val;
console.log(Documents.update(
{
_id: data._id, <<== the document id that I want to update
smallRoom: {
$elemMatch:{
_id : newID._str, <<== the smallRoom id that I want to update
}
}
},
{
$set: obj
}
));
});
好吧,話雖如此,我明白我可以直接插入整個對象,不必推動每一個領域。
但我想這個問題更像是,如果smallRoom有50個字段,並且我想更新3個隨機字段,它是如何工作的? (所以我需要使用_each循環,因爲我不會提前知道哪個字段需要更新,並且不希望替換整個對象)
對不起這個愚蠢的問題......問題是我的代碼沒有工作。在嘗試了更多的事情之後,我意識到我開始推送'smallRomms',然後更新'simpleRooms',這實際上沒有幫助...然後我忘記了設置查詢中''後面的'.'。對不起,我接受你的答案,但可能會刪除該帖子,因爲它不再相關 – mokk