Ajeet
Ajeet

Reputation: 71

Mongodb upsert command in nodejs

I have created a collection named Account.

At first shot, I am inserting around 5 records.

{"Id":"0012800000C6Q19AAF","Name":"Aditya Kumar"}
{"Id":"0012800000C6MldAAF","Name":"GenePoint"}
{"Id":"0012800000C6MlbAAF","Name":"United Oil & Gas, UK"}
{"Id":"0012800000C6MlcAAF","Name":"United Oil & Gas, Singapore"}
{"Id":"0012800000C6MlTAAV","Name":"Edge Communications"}
{"Id":"0012800000C6MlUAAV","Name":"Burlington Textiles Corp of America"}

I am bringing data from the external system, which has already an ID field associated with it.

Again next time when a request comes for inserting extra 5 records, I want to check if Id field of upcoming records already exists in my MongoDB(if yes, then do an update else insert).

And don't get confused by Id field coming from external system with _Id field created for every MongoDB document.

Here is what I have tried:

var x= fields["data"]; obj='Account';
db.createCollection(obj);

db.collection(obj).insert(fields, function(err, doc) {
  if (err) {
    handleError(res, err.message, "Failed to create new contact.");
  } else {
    res.status(201).json(doc.ops[0]);
  }
})

Upvotes: 7

Views: 13905

Answers (1)

Dan Nagle
Dan Nagle

Reputation: 5425

Use the updateOne method:

db.collection.updateOne(
    { _id: id },
    { $set: { name: 'name' } },
    { upsert: true }
);

If a record with the matching id is found then the name field will be updated, otherwise a new record will be created.

Upvotes: 16

Related Questions