Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are all of the possible callback params for mongoose Document#update?

This seems really poorly documented.. The documentation example just has callback being passed to update. There is a link redirecting to Model.update here and the example shows the parameters of the callback are (err, numberAffected, raw).

Does the Document#update callback pass the same parameters? I was hoping to get the updated document returned. My initial search was based on how to update a document in mongo db but even the answer there doesn't explain or even list the params of the callback.

like image 338
JuJoDi Avatar asked Apr 19 '14 17:04

JuJoDi


People also ask

What is callback in Mongoose?

A mongoose query can be executed in one of two ways. First, if you pass in a callback function, Mongoose will execute the query asynchronously and pass the results to the callback . A query also has a . then() function, and thus can be used as a promise.

What is third parameter in Mongoose model?

ref is part of Mongoose's support for reference population. The third parameter to mongoose. model is an explicit collection name.

What is the return type of Mongoose find?

find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries. You don't instantiate a Query directly, Customer.

What is _v in Mongoose?

The “_v” field in Mongoose is the versionKey is a property set on each document when first created by Mongoose. This key-value contains the internal revision of the document. The name of this document property is configurable.


1 Answers

Poor documentation of callback parameters is something that's plagued many node.js libraries for some reason. But MongoDB's update command (regardless of the driver) doesn't provide access to the updated doc, so you can be sure it's not provided to the callback.

If you want the updated document, then you can use one of the findAndModify methods like findOneAndUpdate:

MyModel.findOneAndUpdate({_id: 1}, {$inc: {count: 1}}, {new: true}, function (err, doc) {
    // doc contains the modified document
});

Starting with Mongoose 4.0 you need to provide the {new: true} option in the call to get the updated document, as the default is now false which returns the original.

like image 97
JohnnyHK Avatar answered Oct 23 '22 12:10

JohnnyHK