I have a typical schema and model:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
email: String,
password: String,
profile: {
name: String,
surname: String,
photo: String
},
stats: {
lastLogin: { type: Date, default: Date.now },
loginCount: Number,
lastIP: String
},
source: String,
deleted: Boolean,
dateCreated: { type: Date, default: Date.now }
});
mongoose.model('User', userSchema);
When I perform this update, it only works if I define the callback, else it simply executes but no value is changed in the database:
User.update({email:'[email protected]'}, {$inc: {'stats.loginCount': 1}});
This works:
User.update({email:'[email protected]'}, {$inc: {'stats.loginCount': 1}}, function() {});
Is this a bug? I don't see in the documentation if the callback is required but it's strange to require this… I think i'm missing something here.
Notes: I'm matching by email for testing proposes, I'm using mongoose v3.5.4 in NodeJS v0.8.17 with a simple Express v3.0.6 setup.
Thanks in advance.
Updating Using QueriesThe save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware. For cases when save() isn't flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.
Return value It does not return the updated document but returns a write result.
In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.
The right way to call update
with mongoose is the following:
User.update(query, update).exec(callback);
This way you will be able to skip callback
:
User.update(query, update).exec();
When you calls
User.update(query, update)
it returns a query object.
It's very useful when you querying your database, because you can manipulate with query object before executing it. For example, you can specify a limit
for your find
query:
User.find(query).limit(12).exec(callback);
Update
uses the same mechanism, though its not so useful there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With