我有一个具有以下数据结构的MongoDB
teamName: (String)
data: (Array)
---date: (Timestamp)
---userResults: (Object)
------userHash: (StringHash)
------score: (String)
------comment: (String)
Here is a short example on PasteBin。
给定一个特定的teamName
和date
(在团队数据数组中),我想在{userHash: '', score: '', comment: ''}
数组中添加一个新行(userResults
)。
在查询父节点和父节点父节点后,如何更新给定文档中的数组?
我试过findOneAndUpdate
。它从根目录插入了一个完整的新文档。
TeamRecordSchema.findOneAndUpdate(
{teamName: teamName, data: {date: today}},
{$set:{teamName: teamName, data: {date: today, userResults: [userResponse]}}},
{new: true, upsert: true},
function(err, savedDoc){
// Do stuff with err and savedDoc
});
我已经尝试了save
,并且它再次在我的数据库中创建了一个完整的新文档
const _userResponse = new TeamRecordSchema(teamUserResponse);
_userResponse.save((err, savedDoc) => {
// Do stuff with err and savedDoc accordingly
});
我也根据文档尝试了几种变体,但是我得到的结果相同,或者出错。
任何指针的建议将不胜感激 - 在此先感谢:)
你必须使用$positional
运算符。
您可以在date
中包含字段(data
)来定位元素的索引,并使用更新部件中查询部分中找到的索引替换占位符($
)以推送userResults
中的元素。
TeamRecordSchema.findOneAndUpdate(
{teamName: teamName, 'data.date': today}},
{$push:{'data.$.userResults': {userHash: '', score: '', comment: ''}}},
{new: true, upsert: true},
function(err, savedDoc){ }
);