Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose update without callback

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.

like image 991
Sergi Ramón Avatar asked Jan 30 '13 21:01

Sergi Ramón


People also ask

How do you update a mongoose?

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.

What is update return mongoose?

Return value It does not return the updated document but returns a write result.

What does Upsert do in mongoose?

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.


1 Answers

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.

like image 105
Leonid Beschastny Avatar answered Oct 05 '22 15:10

Leonid Beschastny