Is it possible to do something like this:
var updateData = {
"$set": {
content: 'foo'
},
"$push":{
versions: {
some: 'bar'
}
}
};
Model.update({},updateData, {});
or do we need to do two or more separate updates?
答案 0 :(得分:1)
There is only one update of course and Mongoose itself has nothing to do with it, and just passes through the operation directly. Reading the documentation for $set
should shed a bit more light on this in general.
Your syntax is a bit off and should be:
Model.update({},updateData,function(err,numAffected) {
});
And of course if your wanted to affect multiple documents and not just the first match ( which is the default here ), then pass in "multi":
Model.update({},updateData,{ "multi": true },function(err,numAffected) {
});
The suggestion of .find()
and .save()
is clearly shown to not be what happens here and is completely the wrong way to do this. That operation sequence means "two" operations to touch the database, and most importantly it is possible that data could change in between a .find()
operation and the changes committed in .save()
can overwrite this data.
Operators like $set
with .update()
and related methods are processed atomically. There is one contact with the database only and the point of such operators are to change the data "in place" without needing to return it to the client for modification.
One true statement in comments is to simply turn of debugging:
mongooose.set("debug",true)
And then you will see the actual statements as passed through the driver to MongoDB.
It's just one operation, and depending on the arguments supplied can of course affect multiple fields and even multiple documents.