Reputation: 1744
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.
Upvotes: 14
Views: 12691
Reputation: 51470
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.
Upvotes: 30