2

I am using Nodejs based mongoskin driver for mongo database operation. I want to update my document however don't want to update few fields. Following are more details.

Request for add:

{
  "name": "Theme Name",   
  "description": "Theme Description",
  "createdByUserId": "53651221b25521601a5c9530",    
} 

Request for update:

{
  "_id":"53555ef203dabf282b750a81"
  "name": "Theme Name",
  "categoryId": "53555ef203dabf282b750a81",
  "description": "Theme Description",  
  "createdByUserId": "53651221b25521601a5c9530",
  "updatedByUserId": "5675561b25521601a5c9530",
  "dateCreated": ISODate("2014-05-19T19:47:26.603Z"),
  "dateUpdated": ISODate("2014-05-19T19:49:28.203Z"),
}

I want to ignore following field send by client. 1. createdByUserId 2. dateCreated

For time being I am taking following approach in update operation: 1. Read collection for given _id 2. Read these above two fields from database and update the request and then perform database update operation

Looking help for clean approach.

joy
  • 3,669
  • 7
  • 38
  • 73

1 Answers1

4

Your request for update actually does the following: it replaces everything in the document with the values provided by the request (except for the "_id" of course, which is immutable). What you want is what is called a "partial update" in mongosphere. Please have a look into the $set operator. So what you would do is something like:

db.yourcollection.update({"_id":"53555ef203dabf282b750a81"},
  {$set:
    {
      "categoryId":"53555ef203dabf282b750a81",
      "updatedByUserId":"5675561b25521601a5c9530",
      "dateUpdated":ISODate("2014-05-19T19:49:28.203Z")
    }
  }
)

As far as I know there is now way of sending a complete document to a mongo[s|d] and tell it to only skip certain fields.

Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89
  • Thanks Markus. I am thinking to create wrapper method to iterate each field of document and create query as you suggested. Hopefully this will work. – joy May 21 '14 at 01:25
  • Good to know that this is not supported:-) – joy May 21 '14 at 01:25
  • You should not need to do this. Since you know which fields are to be updated, simply use `$set` on them and you should be good. – Markus W Mahlberg May 21 '14 at 14:19
  • 1
    The link to the blog post in the response is not working. However I googled it and guess the new link is this: https://www.mongodb.com/blog/post/partial-object-updates-will-be-an-important – benjiman Aug 03 '17 at 09:25