Sush
Sush

Reputation: 1457

Issue with updating new row by using the mongodb driver

How can I add a new row with the update operation

I am using following code

statuscollection.update({
    id: record.id
  }, {
    id: record.id,
    ip: value
  }, {
    upsert: true
  }, function (err, result) {
    console.log(err);
    if (!err) {

      return context.sendJson([], 404);
    }
  });

While calling this first one i will add the row id: record.id

Then id:value then i have to add id:ggh

How can i add every new row by calling this function for each document I need to insert

Upvotes: 0

Views: 40

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151122

By the structure of your code you are probably missing a few concepts.

  1. You are using update in a case where you probably do not need to.
  2. You seem to be providing an id field when the primary key for MongoDB would be _id. If that is what you mean.

If you are intending to add a new document on every call then you probably should be using insert. Your use of update with upsert has an intended usage of matching a document with the query criteria, if the document exists update the fields as specified, if not then insert a new document with the fields specified.

Unless that actually is your goal then insert is most certainly what you need. In that case you are likely to rely on the value of _id being populated automatically or by supplying your own unique value yourself. Unless you specifically want another field as an identifier that is not unique then you will likely want to be using the _id field as described before.

Upvotes: 1

Related Questions