Introducing MongoDB Chapter 3
The third parameter has a callback function attached to it. This function takes two
parameters, unlike the create method. The first parameter handles the error. If, somehow,
the execution is not done successfully, it returns an error and we can customize it the way
we want. The second parameter is the important one here; it returns the response when the
execution is successfully done. In this case, the users parameter is an array of objects that
are retrieved from the users collection. The output of this call would be:
users: [
{
name: 'John Doe',
email: '[email protected]'
}
]
Now we have all the records from the users collection.
Fetching a specific record
This is also as simple as fetching all records from a collection. We talked about using
find() in the previous section. To fetch a single record, we have to use findById() or
findOne(), or we can also use the where query. The where query is the same as we talked
about previously when we had to pass a parameter to fetch records that fell under the same
category.
Let's move ahead on using the following query:
User.findById(1, 'name email', function (error, user) {
if (error) { console.error(error); }
res.send(user)
})
As you can see, the syntax for both find() and findById() are similar. Both take the
same amount of parameters and behave the same. The only difference between these two is
that the preceding find() method returned an array of records as a response, whereas
findById() returns a single object. So, the response to the preceding query would be:
{
name: 'John Doe',
email '[email protected]'
}
That's it – simple!