0

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 enter image description here

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 enter image description here

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

2
  • Is there is anything in err object ? Print it add . Also add what nitem[0] contains . Add what they have in question . Commented Jan 4, 2018 at 5:55
  • Hi I have updated the question. Commented Jan 4, 2018 at 6:04

1 Answer 1

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);
})
Sign up to request clarification or add additional context in comments.

4 Comments

i am using Mongojs, so i assuming it will be findAndModify?
I tried, the result it return as What i need! However, When I query all players info. It still showing empty object under finditem array as I have put the picture above. Do you know any reason why?
make sure while test in mongo shell use .... {$ne : ObjectId(nitem[0]._id) } and test with a new record so debug can easy
I found the problem which related to another issue. thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.