COVID19 Lockdown Dev Log – Day 32, Building Models In Mongoose

What I Worked On

A taskmanager app in Nodejs.

What I Learned

I learned about working with Mongoose, which is an ODM (Object Data Modeling) library that provides easier use of MongoDB in Nodejs. It reduces a lot of the MongoDB boilerplate you would need to write yourself 😀

In regards to working on a taskmanager app, I had to write a model for my data using Mongoose. It’s fairly straight forward. Let’s require Mongoose in the script and open a connection to the MongoDB database that I have locally on my machine:

const mongoose = require('mongoose');

// create connection string AND database name after portnumber
const connectionUrl = 'mongodb://127.0.0.1:27017/task-manager-api'

mongoose.connect(connectionUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})

The object passed in the connect() function is an ‘options’ object, which takes care of deprecated APIs in MongoDB (More info about that is in the Resources). Now, let’s create a model for a Task:

const Task = mongoose.model('Task', {
    description: {
        type: String,
        required: true,
        trim: true,
    },
    completed: {
        type: Boolean,
        default: false
    }
})

Here I define a Task model that will tell how each task’s data will look like. Mongoose provides some lovely options like type, required and default. The two first might be selfexplanatory, but the last of them, trim, basically “trims” the input for whitespace 😀

Now, let’s try and make a Task and add it to the database:

const firstTask = new Task({
    description: 'Build a native app during lockdown',
    completed: false
})

// because the Mongoose API 'save()' returns a Promise, we can save it to the database like so:
firstTask.save().then(() => {
    console.log(firstTask)
}).catch((error) => {
    console.log("Error on save!", error)
})

And there we have it! We can use a tool called Robo 3T to view our MongoDB database in a GUI. Note that __v is provided by Mongoose by default to monitor the version of the document(also called a ‘row’ in SQL). The _id is provided by MongoDB as an identifier for the document.

That’s it. It’s Friday so I’ll leave you with a “have a nice weekend” 😀

What Distracted Me During The Day