Mongoose,如何在现有的JSON文档中将元素追加到数组中

问题描述 投票:1回答:1

The Situation

我有一个具有以下数据结构的MongoDB

teamName: (String)
data: (Array)
---date: (Timestamp)
---userResults: (Object)
------userHash: (StringHash)
------score: (String)
------comment: (String)

Here is a short example on PasteBin


The Question

给定一个特定的teamNamedate(在团队数据数组中),我想在{userHash: '', score: '', comment: ''}数组中添加一个新行(userResults)。

在查询父节点和父节点父节点后,如何更新给定文档中的数组?


What I've tried so far

我试过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     

 });

我也根据文档尝试了几种变体,但是我得到的结果相同,或者出错。


任何指针的建议将不胜感激 - 在此先感谢:)

node.js mongodb mongoose
1个回答
1
投票

你必须使用$positional运算符。

您可以在date中包含字段(data)来定位元素的索引,并使用更新部件中查询部分中找到的索引替换占位符($)以推送userResults中的元素。

TeamRecordSchema.findOneAndUpdate( 
  {teamName: teamName, 'data.date': today}}, 
  {$push:{'data.$.userResults': {userHash: '', score: '', comment: ''}}}, 
  {new: true, upsert: true}, 
   function(err, savedDoc){ }
);
© www.soinside.com 2019 - 2024. All rights reserved.