Implementing the count method
Now, we're going to go ahead and implement count over inside of Atom. What I'm going to do is take the current query, copy it to the clipboard, and then comment it out. I'm going to go ahead and replace our call to toArray with a call to count. Let's go ahead and remove the query that we pass in to find. What we're going to do here is count up all of the Todos in the Todos collection. Instead of having a call to toArray, we're going to have a call to count instead.
db.collection('Todos').find({}).count().then((count) => {
As you saw inside of the examples for count, they call count like this: calling count, passing in a callback function that gets called with an error, or the actual count. You can also have a promise as a way to access that data, which is exactly what we did with toArray. In our case, instead of passing a callback function like this, we're going to use the promise instead. We already have the promise set up. All we need to do to fix this is change docs to count, and then we're going to remove the console.log caller where we print the docs to the screen. Right after we print Todos, we're going to print Todos count, with a colon passing in the value.
db.collection('Todos').find({}).count().then((count) => { console.log('Todos count:'); }, (err) => { console.log('Unable to fetch todos', err); });
This is not a template string, but I am going to go ahead and swap it out with one, replacing the quotes with `. Now, I can pass in the count.
db.collection('Todos').find({}).count().then((count) => { console.log(`Todos count: ${count}`); }, (err) => { console.log('Unable to fetch todos', err); });
Now that we have this in place, we have a way to count up all of the Todos in the Todos collection. Inside the Terminal, I'm going to go ahead and shut down our previous script and rerun it:
We get Todos count too, which is correct. The cursor that we have, a call to find, returns everything in the Todos collection. If you count all of that up, you're going to get those two Todo items.
Once again, these are count and toArray; they're just a subset of all of the awesome methods you have available to you. We will be using other methods, whether it be the MongoDB native driver or, as you'll see later, the library Mongoose, but for now let's go ahead and do a challenge, given what you know.