Ziarno
Ziarno

Reputation: 7562

Node.js + Mongodb: is it possible to invoke 'save' on a data returned from a database?

db.users.findOne({}, function (err, user) {
  //update or add a field
  user.name = 'Phil';
  //is the next line possible?
  user.save(); //error :(
});

is there a function like 'save' so that my changes to 'user' will be save in the db?

Upvotes: 0

Views: 29

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311925

You can use the save method on the collection to do that:

db.users.findOne({}, function (err, user) {
  user.name = 'Phil';
  db.users.save(user);
});

It performs a full document replacement by _id, so using an update with {$set: {name: 'Phil'}} would be more efficient in your example.

Upvotes: 2

AlbertEngelB
AlbertEngelB

Reputation: 16446

I don't think this is possible with the native driver.

This sort of syntax works fine if you use Mongoose as a MongoDB driver.

Upvotes: 0

Related Questions