Monday 4 January 2021

Mongoose/Mongodb findOneAndUpdate while keeping what is already there

I'm saving many items per User in my db via mongoose, items end inside item (array) in the User schema. How do I tell mongodb to findOneAndUpdate while keeping the items that are already there? Because right now the update basically override the whole item array in the db for that User.

What I have is this:

            var filter = { 'id': thisId };
            let update = { 
              'item': itemsArray,
              'updatedAt': Date.now()
            };

            User.findOneAndUpdate(filter, update, {upsert: true, new: true}, function(err, doc) {
                if (err) return res.send(500, {error: err});
                return;
            });

I've read about the $addToSet in the mongodb docs, but is it what I need here? How can I apply it to my query?

UPDATE: the $set as suggested below doesn't work. My example: I fetch 400 items inside the field 'item', then with a conditional based on last update date, I fetch 50 items the second time, now let's say among these 50 there's one item which is not already present among the 400 previously added, I'm expecting it to add the item to the 400 becoming 401. Instead what happens is i now find 50 items total inside the 'item' field

SOLUTION I FOUND:

User.findOneAndUpdate(filter, { $set : {'updatedAt': Date.now()}, $addToSet : {'item': itemsArray} }, {upsert: true}, function(err, doc) {
                    if (err) return res.send(500, {error: err});
                    return;
                });


from Mongoose/Mongodb findOneAndUpdate while keeping what is already there

No comments:

Post a Comment