0

I'm new in here and I've just started to uses mongodb recently. I have a problem, I'm trying to update a collection's item in a given model if the item exists or update it if not.

I tried the following code but it's not working:

const res = await this.userModel.findByIdAndUpdate({ 
        _id: user.id,
        // 'devices.name': 'postman2'
    }, {
        $addToSet: { 'devices.[]': { name: 'postman2', generatedSecret: generatedSecret } }
    }, { new: true, upsert: true }).exec();

My document looks like this:

{
    "_id": {
        "$oid": "5e9c6ffe9463db1594a74bec"
    },
    "email": "john.doe@mail.com",
    "logins": [{
        "provider": "email",
        "secret": "sha1$e3d548b5$1$6f1b28e6b7cef47ca27b4e55ddbb6a5b8bc6b0ce"
    }],
    "devices": [{
        "_id": {
            "$oid": "5e9ddc9adb866666845bf86b"
        },
        "name": "postman",
        "generatedSecret": "$2b$10$7fmneXGS1FjKyPXBa2Ea1erQfXF3ALjylIxOhetA9yxc3S95K4LVO"
    }],
    "applications": [{
        "applicationId": "5e9c8b7c9463db1594a74bed"
    }]
}

I want to update that devices item which matchs the query conditions. But if there isn't any matched result, then insert a new item with searched parameters.

Is possible to do this in one command?

Thanks!

  • Here is a similar post with answers: [mongoose update array or add to the array](https://stackoverflow.com/questions/61234012/mongoose-update-array-or-add-to-the-array) – prasad_ Apr 21 '20 at 02:22
  • What does "not working" mean? – D. SM Apr 21 '20 at 02:22

0 Answers0