Donald
Donald

Reputation: 3911

Mongodb Update Query Deletes All Array Fields Except Field Specified in Command

I'm using Node, MongoDB, and Mongoose. I've checked the MongoDB docs on set and update. I've Googled for a little over an hour now and I've found topics that dance around my issue, nothing definitive though. The query below updates the correct field, but it also completely removes the other fields in the array I haven't specified.

db.posts.update( 
  { "_id" : { $exists : true }  },
  { $set : { userCreated : { "time" : new ISODate("2013-07-11T03:34:54Z") } } },
  false,
  true
)

This is the section of the schema I'm trying to modify:

},
userCreated: {
  id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  name: { type: String, default: '' },
  time: { type: Date, default: Date.now }
},

This is what comes out:

},
"userCreated": {
  "time": { ISODate("2013-07-11T03:34:54Z") }
},

Upvotes: 1

Views: 563

Answers (1)

go-oleg
go-oleg

Reputation: 19480

You can update the time property of userCreated and leave the other properties alone by using dot notation:

db.posts.update( 
  { "_id" : { $exists : true }  },
  { $set : { "userCreated.time" : new ISODate("2013-07-11T03:34:54Z") } },
  false,
  true
)

Upvotes: 3

Related Questions