Advanced Node.js Development
上QQ阅读APP看书,第一时间看更新

Writing a query to fetch completed todos

To get this done, inside of Atom, we're going to make a change to how we call find. Instead of passing in 0 arguments, we're going to pass in 1. This is what's known as our query. We can start specifying how we want to query the Todos collection. For example, maybe we want to query only Todos that have a completed value equal to false. All we have to do to query by value is set up the key-value pairs, as shown here:

db.collection('Todos').find({completed: false}).toArray().then((docs) => {

If I rerun our script over in the Terminal after shutting it down, we get just our one Todo item:

We have our item with the text equal to Something to do. It has a completed status of false, so it shows up. Our other Todo with a text property of Walk the dog is not showing up because that one has been completed. It doesn't match the query, so MongoDB does not return it. This is going to come in handy as we start querying our documents based off of completed values, text properties, or IDs. Let's take a quick moment to look at how we can query one of our Todos by ID.