Getting started with Mongoose
As I’m learning NodeJS, a runtime environment, I’m learning more about different technologies that get operations done that Im familiar with which makes the learning process a whole lot easier.
So far, we’ve learned about MongoDB, a non-relational database. Naturally, with the use of any database, we look for ORM’s or ODM’s. These are programming techniques for converting data between two incompatible systems. It lets you query and manipulate data from a database using the object-oriented paradigm. This especially became useful during my time at a bootcamp as I didn’t not want to use Sinatra every time I wanted to interact with my database.
Mongoose is an ODM, or an Object Data Modeling library which will allow us to do all CRUD operations within or database. First thing’s first, let’s import it.
npm i mongoose
Before getting started with code, make sure you have your Mongo DB up and running as well as Robo T3 as we’ll be using this to see the changes we’ve made to out file. Create a file with any name, I gave it ‘mongoose.js’, and require the ODM.
const mongoose = require('mongoose');mongoose.connect('mongodb://127.0.0.1:27017/task-manager-api',{
useNewUrlParser: true ,
useCreateIndex: true
})
Similar to MongoClient.connect(), mongoose.connect() establishes a connection to a given url, in this case ‘mongodb://127.0.0.1:27017/task-manager-api’ where /task-manager-api is the name of our database.
The next thing we’ll create are some models to start creating instances and manipulating our database. In this case, since I’m working on a task manager api, I’ll create a task model.
const Task = mongoose.model('Task', {
description:{
type: String,
trim: true
required: true
},
completed:{
type: Boolean
default: false
})
Mongoose.model takes two arguments. The name of a collection and an object describing the attributes of the model. Each attribute has a value of an object that also describes some parameters you’d like to describe as you create them. Let’s create a task.
const task1 = new Task({
description: "Complete homework by next week"
completed: false
})task1.save().then(()=>{
console.log(task1)
}).catch((error)=>{
console.log('Error', error)
After creating the task, you’ll notice I chained some functions to task1. We can use .save() which is given to us through mongoose. We take advantage of using promises to error handle. We console.log the task if it successfully saves to the database and use .catch() to console.log the errors if they exist.
After this is ran using, you can use Robo T3 to check that your task was indeed saved. It should look like an object as such.
{
description: "Complete homework by next week",
completed: false
}
That’ll be it for this short introduction as I’m learning more as I go. Creating models was something that I somewhat dreaded but this intro makes it so much more fun. I may have a preference in using NodeJS instead of Ruby at this point so we’ll see what I build out with it!