我的node.js應用程序會將子文檔插入到下面的MongoDB文檔的嵌套子文檔數組字段中,並且需要確定ID新插入的子文件:在MongoDB文檔子文檔數組中插入並返回子文檔的ID
{
"_id" : ObjectId("578d5a52cc13117022e09def"),
"name" : "Grade 5 - Section A",
"scores" : [{
"studentId" : ObjectId("5776bd36ffc8227405d364d2"),
"performance" : [{
"_id" : ObjectId("57969b8fc164a21c20698261"),
"subjectId" : ObjectId("577694ecbf6f3a781759c54a"),
"score" : 86,
"maximum" : 100,
"grade" : "B+"
}]
}]
}
子文件看起來是這樣的:
{
"subjectId" : ObjectId("5776ffe1804540e29c602a62"),
"score" : 74,
"maximum" : 100,
"grade" : "A-"
}
我使用下面的代碼貓鼬添加子文檔:
Class.update({
_id: '578d5a52cc13117022e09def',
'scores.studentId': '5776bd36ffc8227405d364d2'
}, {
$addToSet: {
'scores.$.performance': {
'subjectId' : '5776ffe1804540e29c602a62',
'score' : 74,
'maximum' : 100,
'grade' : 'A-'
}
}
}, function(err, result) {
if (err) {
throw err;
}
console.log(result);
});
的受試者子文檔獲取performance
子文檔陣列本身是嵌套在scores
子文檔陣列中加入。請注意,新插入的子文檔被分配了自己的ID,由定義的模式制定。即使我拿回整個文件,這也不是很有幫助。我特別需要該新插入的子文檔的ID。對這個問題推薦的方法是什麼?
相關http://stackoverflow.com/questions/18760087/find-id-of-latest-subdocument-inserted-in-mongoose – chridam