Once you have the Schema
object compiled into a Model
object, you are completely ready to begin accessing, adding, updating, and deleting documents in the model, which makes the changes to the underlying MongoDB database. However, before you jump in, you need to understand the nature of the Query
object provided with Mongoose.
Many of the methods in the Model
object match those in the Collection
object defined in Chapter 13. For example, there are find()
, remove()
, update()
, count()
, distinct()
, and aggregate()
methods. The parameters for these methods are for the most part exactly the same as for the Collection
object, with a major difference: the callback
parameter.
Using the Mongoose Model
object, you can either pass in the callback function or omit it from the parameters of the method. If you pass in the callback function, the methods behave as you would expect them to. The request is made to MongoDB, and the results are returned in the callback
function.
However, if you do not pass in a callback function, the MongoDB request is not sent; instead, a Query
object is returned, allowing you to add additional functionality to the request before executing it. Then when you are ready to execute the database call, you use the exec(callback)
method on the Query
object.
To better understand this, the following example of a find()
request in Mongoose uses the same syntax as in the native driver:
model.find({value:{$gt:5}},{sort:{[['value',-1]]}, fields:{name:1, title:1,
value:1}}},
function(err, results){});
However, when you use Mongoose, you can define all the query
options separately, using the following code:
var query = model.find({});
query.where('value').gt(5);
query.sort('-value'),
query.select('name title value'),
query.exec(function(err, results){});
The model.find()
call returns a Query
object instead of performing the find()
because no callback is specified. Notice that the query
properties and options
properties are broken out in subsequent method calls on the Query
object. Then, once the Query
object is fully built, the exec()
method is called, and the callback function is passed into that.
You can also string the Query
object methods together, as in this example:
model.find({}).where('value').lt(5).sort('-value').select('name title value')
.exec(function(err, results){});
When exec()
is called, the Mongoose library builds the necessary query
and options
parameters and then makes the native call to MongoDB. The callback function returns the results.