In this post, we will learn how to get data from a collection using Express.js and MongoDB.
Usually, this is the first thing you learn how to do when you are learning MongoDB.
The syntax is as follows:
Model.find({/*your search criteria*/})
Model is the name of the model (meaning collection of things: names, users, fruits, cars, etc), and inside of {}, you write the search criteria for your query inside the brackets.
For example, if I want to search a collection of Names with 8 names and would like all the rows with firstname (let's set the column name of "first name" as "firstname") of John, we would write the following code.
var johns = await Names.find({"firstName":"John"});
In our code above, we are searching a collection of names(“Name”) for all the rows that have a “firstName” column equal to “John” and then we are returning all of them as a collection named johns. johns, regardless of how many results we find(even if we find only one), will be a collection.
As with lots of things in node.js, don’t forget to add the keyword await
in front of your query and async
in front of the function where await is located in.
Accessing Our Results
To display a specific result, we would write something like johns[0], which would get us the first result (Name with firstName of "John"). To get the second “Name with firstname of John” (if any), we would use johns[1].
To access a specific property of john[0], we would write johns[0]["firstName"], which should return “John” since all of our results "must have a firstName of John".