简体   繁体   中英

Mongodb $addToSet an object into nested array

I have tried to insert an object into an array inside another array which it only insert an empty object.

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

nitem[0] is an object.

however, the result I found from the database is like this 在此处输入图片说明

I have tried to insert value into this array , it worked but not with object. I have done some research but I found nothing.

I hope someone here can help me! thanks.

===Updated=== Nitem[0] contain information of the item i want to put into the array "finditem". It looks like this 在此处输入图片说明

There is not err return for this, everytime I update, it says {ok:1, nModified:1, n:1}

$addToSet doesn't compair whole object. this is not mongo feature currently. It's a little tricky. you can do it like 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);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM