Fork me on GitHub

Queries

Documents can be retrieved through several static helper methods of models.

Any model method which involves specifying query conditions can be executed two ways:

When a callback function:

Let's take a look at what happens when passing a callback:

var Person = db.model('Person', yourSchema);

// find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
  if (err) return handleError(err);
  console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.
})

Here we see that the query was executed immediately and the results passed to our callback. Now let's look at what happens when no callback is passed:

// find each person with a last name matching 'Ghost'
var query = Person.findOne({ 'name.last': 'Ghost' });

// selecting the `name` and `occupation` fields
query.select('name occupation');

// execute the query at a later time
query.exec(function (err, person) {
  if (err) return handleError(err);
  console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.
})

An instance of Query was returned which allows us to build up our query. Taking this example further:

Person
.find({ occupation: /host/ })
.where('name.last').equals('Ghost')
.where('age').gt(17).lt(66)
.where('likes').in(['vaporizing', 'talking'])
.limit(10)
.sort('-occupation')
.select('name occupation')
.exec(callback);

References to other documents

There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where query#populate comes in. Read more here.

Streaming

Queries can be streamed from MongoDB to your application as well. Simply call the query's stream method instead of exec to return an instance of QueryStream.

Next Up

Now that we've covered Queries, let's take a look at validation.