首页 文章

使用push MongoDB将字符串添加到嵌套数组

提问于
浏览
0

嘿我想在Api NodeJS中使用MongoDB的push函数将字符串添加到嵌套数组中 .

router.post('/add-member-to-card', (req, res) => {

    Board.findOneAndUpdate({ _id: req.body.idBoard }, 
        {
            "$push": { ['lists.' + req.body.indexList + '.cards.' + req.body.indexCard + '.members'] : { $each: req.body.member, $position: 0 }   }, 
            "$push": { "activity" : { $each: [req.body.activity], $position: 0 }   }, 
        },
            { upsert: true },
        ((err, updated) => {
            if (err) { console.log(err) }
            else { 
                console.log(req.body.member);
            }
        })
    );
});

第二次推动是有效的,但首先是错误的 . 一般来说,我正试图这样做,也许不能这样做?我的意思是将项目添加到嵌入式阵列?

req.body.member的容器是 - > da7sda68ds6ad87asd68da

编辑

我接受了第一次$ push:

// "$set": { ['lists.' + req.body.indexList + '.cards.' + req.body.indexCard + '.members']: req.body.members },

这行得通 /\

1 回答

  • 0

    也许问题是你对字段 $push 有多个定义 . 这与以下相同:

    let foo = {
        a: 1,
        a: 2
    };
    

    尝试将其写为:

    {
        $push: {
               ['lists.' + ... + '.members'] : { $each: req.body.member, $position: 0 },
               "activity" : { $each: [req.body.activity], $position: 0 } 
           },
      }
    

    也许这会有所帮助

相关问题