在MongoDB文档子文档数组中插入并返回子文档ID [英] Insert and return ID of sub-document in MongoDB document sub-document array
问题描述
我的node.js应用会在下面MongoDB文档的嵌套子文档数组字段中插入一个子文档,我需要确定新插入的子文档的ID:
My node.js application will insert a sub-document into a nested sub-document array field of the following MongoDB document, and I need to determine the ID of the newly inserted sub-document:
{
"_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 代码添加子文档:
I am adding the sub-document using the following Mongoose code:
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.解决此问题的推荐方法是什么?
The subject sub-document gets added in the performance
sub-document array which is itself nested in the scores
sub-document array. Notice that the newly inserted sub-document is assigned with its own ID, as instituted by the defined schema. Even if I get back the entire document, that's not very helpful. I specifically need the ID of that newly inserted sub-document. What is the recommended approach to this problem?
推荐答案
在这种情况下,我更喜欢将 ID 预先分配给子文档(即 sub._id = ObjectId()
或使用uuid
包(如果您喜欢 uuid):清晰且可预测.
In this case I prefer pre-assign the ID to the sub-document (i.e. sub._id = ObjectId()
or use uuid
package if you prefer uuid): is clear and predictable.
还请记住,如果您经常通过 subdoc id 进行查询,最好在集合中为此用例添加(使用 ensureIndex()
)索引.
Also remember that if you frequent query by a subdoc id is good to add (using ensureIndex()
) an index for this use case in the collection.
这篇关于在MongoDB文档子文档数组中插入并返回子文档ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!