Mongodb $ addToSet将一个对象嵌入到嵌套数组中

时间:2018-01-04 05:49:47

标签: arrays mongodb mongojs

我试图将一个对象插入到另一个数组中的数组中,该数组只插入一个空对象。

db.players.update({ username: crUserName }, { $addToSet: { finditem: nitem[0] } },{upsert:true} , function (err, doc)

nitem [0]是一个对象。

但是,我从数据库中找到的结果是这样的 enter image description here

我试图在这个数组中插入值,但是它没有用于对象。 我做了一些研究,但我一无所获。

我希望有人能帮助我!感谢。

===更新=== Nitem [0]包含我想要放入数组“finditem”的项目的信息。 看起来像这样 enter image description here

每次更新时都没有错误的回报, 它说{ok:1,nModified:1,n:1}

1 个答案:

答案 0 :(得分:1)

$ addToSet并不会影响整个对象。目前这不是mongo功能。这有点棘手。你可以像somting那样做。

Player.findOneAndUpdate({
        username: crUserName,
        "finditem._id" : {$ne : nitem[0]._id }
    },
    {
        // addToSet insert if nitem _id not exists .
        $addToSet: {
            finditem: nitem[0]
        }
    },
    {
        upsert: false,
        new: true
    },(err, results)=>{
        console.log(err, results);
})
相关问题