Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

Fetching records from Mongoose


Now that we have successfully created a user, we have a record in the users collections in


the database. There are two ways to fetch this record in our client: fetch all the records of
users that we have or fetch a specific user.


Fetching all records

There are lots of methods that come out of the box with a Mongoose model to make our
lives easier. Two such methods are find() and findById(). In MongoDB, we saw how


we could retrieve a collection's records data via raw MongoDB queries. This is similar, the


only difference being that Mongoose has a very easy way to do it. I recommend you learn


MongoDB first instead of Mongoose because MongoDB gives you an overall idea of what a
database is and you will learn the fundamentals of the database and about its queries.


Mongoose just adds a layer on top of MongoDB to make it look a little bit easier for faster
developments.


With that, let's look into the code snippet here:


User.find({}, 'name email', function (error, users) {
if (error) { console.error(error); }
res.send({
users: users
})
})

The Mongoose model User calls a method called find(). The first parameter is our query


string, which is left empty: {} in the preceding query. So, if we want to retrieve all users


who share the same name, say, Peter, then we can replace that empty {} with { name:


'Peter'}.


The second parameter denotes which fields we want to retrieve from the database. We can
leave it blank if we want to retrieve all fields or we can just specify it here. For this example,


we are just retrieving user names and emails.

Free download pdf