Chris Williams
Chris Williams

Reputation: 432

Meteor/MongoDB update all fields for entry

I'm using Mongo with Meteor and have wrote a basic CRUD, but wanted to know if it's possible to update all fields in an entry. I can only seem to update a specific field in an entry, like this:

Brief.update(briefObject._id, { $set: { description: briefObject.description} });

Is it possible to update the entire entry by passing in the whole object? I'm trying to keep my code dry and not have to write different functions to update different fields for an entry. Something like this:

Brief.update(brief._id, { $set: briefObject }

Here's an output of an example of an entry:

meteor:PRIMARY> schema = db.briefs.findOne();
{
    "_id" : "a56xpJ3ZTAzZKFmwD",
    "title" : "Foo",
    "client" : "Bar",
    "deadline" : ISODate("2017-01-01T12:00:00Z"),
    "description" : "Lorem Ipsum Dolor Sit",
    "createdAt" : ISODate("2016-01-15T16:20:46.403Z"),
    "username" : "fooBar"
}

Here's an example of briefObject:

{ title: 'Foo',
  client: 'Bar',
  deadline: Sun Jan 01 2017 12:00:00 GMT+0000 (GMT),
  description: 'Lorem Ipsum Dolor Sit Amet',
  createdAt: Fri Jan 15 2016 16:20:46 GMT+0000 (GMT),
  username: 'fooBar',
  _id: 'a56xpJ3ZTAzZKFmwD',
  '$$hashKey': 'object:4' 
}

Upvotes: 3

Views: 723

Answers (1)

chridam
chridam

Reputation: 103355

You can recreate the update object to use in the $set operator by removing the other two keys _id and $$hashKey before using it in the update. With this approach you don't have to recreate all the properties in the object, just delete the reserved keys from the new object and you're good to go.

You can create the selector and modifier objects that you can use in your update as in the following example:

var selector = { "_id": briefObject._id },
    modifier = { "$set": briefObject };

delete modifier["$set"]["_id"];
delete modifier["$set"]["$$hashKey"];

Brief.update(selector, modifier);

Upvotes: 1

Related Questions