Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert if not exists, if exists update [duplicate]

I'm getting usersfrom this API.

https://redmine-mock-api.herokuapp.com/api/v1/users

There are 100 in total (100 different ids). I added them to my mongodb database using mongoose but the problem is that it's always adding (i already have 5000 users (50 times repeated 100 users)

I want to add if the id does not exist or update if it exists.

What am I doing wrong? users is the array of users from the API

 db.collection("users").insertMany(users, function (error, response) {
                        if (error) throw error;
                        console.log("Number of users inserted: " + response.insertedCount);
                        db.close();
                    });
like image 858
John Avatar asked Jan 26 '26 02:01

John


1 Answers

try following format

db.collection.update({'_id': Id}, //Find with the unique identifier
                     {//put whatever you want to insert},
                     {upsert: true}
                    )
like image 72
Priyanka Kariya Avatar answered Jan 28 '26 18:01

Priyanka Kariya