Check out bidbear.io Amazon Advertising for Humans. Now publicly available 🚀

Mongoose Queries

Contents

.countDocuments

This is a method used to count the instances of an item in a collection: Mongoose API Docs: .countDocuments

For example if I want to count the number of users in my database that have the role of “Administrator” I could do the following.

User.countDocuments({ role: 'Administrator' },(err, count) => {
    if(err){
        console.log(err);
    } 
    console.log('There are: ' + count + ' Administrators' );
});

And that is based on this schema.

// Mongoose Schema for users
const userSchema = new mongoose.Schema({
    firstname: String,
    lastname: String,
    email: String,
    role: String,
    username: String,
    password: String
});
module.exports = mongoose.model("User", userSchema);

.equals()

When it comes to comparing the user ID of the author and the user we must be a bit careful. You would think that we could compare the foundBlog.author.id with req.user._id, and if you console logged both of them they would be identical. But this is a special use case where req.user._id is a standard string, but foundBlog.author.id is a Mongoose Object. This is just something that you need to know, any attempt to compare these with === or == will always fail.

To solve this Mongoose has provided us with a method just for this purpose, .equals. So instead of this

if(foundBlog.author.id === req.user._id){
// do something
}

we will do this

if(foundBlog.author.id.equals(req.user._id)){
// do something
}

And then we can chain these together into a new route like this

// edit blog form
router.get("/:id/edit", (req, res) => {
    // is user logged in?
    if(req.isAuthenticated()){
    // find blog with provided ID
        Blog.findById(req.params.id,(err, foundData) => {
            if(err){
                console.log(err);
            } else {
                // does user ID match user ID of author?
                if(foundData.author.id.equals(req.user._id)){
                    // render single blog template with that post data
                    res.render("editBlog.ejs", {blog: foundData});
                } else {
                    res.send("You are not authorized to do that.");
                }
            }
        });
    }    
});

Testing this shows that we can successfully reach the edit form for blogs that are our own, but not for others. Trying to edit blogs that were created with seed data crashes the application though, because they don’t have real user ID’s, just usernames we manually input. We can fix that later.

Amazon Ad Analytics For Humans

Advertising reports automatically saved and displayed beautifully for powerful insights.

bidbear.io
portfolios page sunburst chart