0

I'm trying to update a collection field and add a new data to a subdocument(array). Is there anyway it can be done in one call?

I want to update an document from:

{
last_modified:dateObj,
subDoc:[]
}

To the following:

{
last_modified:new DateObj,
subDoc:[{newObj:newObj}]
}
simmu
  • 83
  • 1
  • 5

1 Answers1

2

Assuming your schema is as follows:

var Data = new Schema({
  last_modified : Date,
  subDoc : [Schema.Types.Mixed]
});

Then you can modify in one method call (I will be using Mongoose's concept of methods):

Data.methods.addDocument = function(newObj, cb){
    this.last_modified = Date.now();
    this.subDoc.push(newObj);
    this.save(cb);       
}

This operation will be atomic, e.g., both last_modified and subDoc will be modified, or none of them will.

Community
  • 1
  • 1
verybadalloc
  • 5,768
  • 2
  • 33
  • 49
  • This is what I'm looking for. Thanks for the answer and also formatting the question for me. – simmu Dec 25 '13 at 00:19
  • Hi @verybadalloc! about 'atomic'. Do you mean javascript is one thread so it is atomic? Or addDocument will atomic even if we have multiple javascript process? – damphat Dec 25 '13 at 02:10
  • @damphat [Atomicity](http://stackoverflow.com/questions/3740280/acid-and-database-transactions) is one property of a DB system, and is independent of the number of processes. By atomicity, I mean that the whole `addDocument` function will either execute fully (thus updating the doc), or fail. In either case, the data in the db is still consistent, even in case of an error. More information can be found [here](http://docs.mongodb.org/manual/tutorial/isolate-sequence-of-operations/) – verybadalloc Dec 25 '13 at 03:02