Worp
Worp

Reputation: 1018

mongoose update not calling back instantly

I am sure this is simply a misunderstanding, but I can't figured it out :/

I am trying to update a document in mongoDB, using mongoose on a node server.

My code looks like this:

Message.update(searchQuery, updateQuery, function(err, response)
{
    if(err) return handleError(err);
    if(response) console.log(util.inspect(response));
});

When I first call this function, the callback is not executed and no changes are applied to the database. Effectively, the update does not happen.

When I call the function a second time, the callback from the first call returns and the changes from the fist update are applied to the DB. The callback for the second call does not return though and no changes for the second call are apllied.

When I call it for the third time, callback 2 returns and changes 2 are applied, but not callback and changes 3. And so on...

I assumed it has something to do with the mongoose function not directly executing when no callback is specified, so I tried adding an empty "options" array:

Message.update(searchQuery, updateQuery, **{}**, function(err, response){...});

or executing the update explicitly:

Message.update(searchQuery, updateQuery).exec( function(err, response){...});

The results were unchanged though.

Upvotes: 1

Views: 504

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

Missing Mongoose callbacks are typically caused by the update waiting for the connection to be opened, as any calls to update, save, find, etc. will be queued up by Mongoose until the mongoose.connect call has completed.

So ensure your mongoose.connect call is being made before your call to update.

Upvotes: 1

tuvokki
tuvokki

Reputation: 740

The right way to call update with mongoose is the following:

Message.update(query, update).exec(callback);

Whats exactly in your updateQuery?

Upvotes: 0

Related Questions