【发布时间】:2023-04-05 04:34:01
【问题描述】:
我的node.js应用程序会在下面的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-"
}
我正在使用以下 Mongoose 代码添加子文档:
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);
});
subject 子文档被添加到 performance 子文档数组中,该数组本身嵌套在 scores 子文档数组中。请注意,新插入的子文档分配有其自己的 ID,如定义的模式所规定的那样。即使我取回整个文档,这也不是很有帮助。我特别需要那个新插入的子文档的 ID。解决此问题的推荐方法是什么?
【问题讨论】: