Getting Started with MongoDB CRUD using Mongoose and NodeJS

Objective

Get introduced to the mongoose module of NodeJS and perform CRUD operations

Prerequisite

Getting Started

Install Pakages

Create and open the project folder where you would write and execute your project in VS Code (or any other text editor of your choice). To open the text editor from terminal,CMD or bash execute:

code <Project Folder path>

Create a file index.js where we will code. Initialise npm which is Node Package Manager and install the packages -

  • mongoose - Help us santize and validate data and connect the MongoDB database.
  • validator - Will help in validation of data.
npm init
npm install validator mongoose

Start MongoDB

To start the database execute in terminal/bash/cmd:

mongod

Start Coding

Import the mongoose and the validator module.

const mongoose = require('mongoose')
const validator = require('validator')

Connecting to the database

db.js will play the role of connecting to our mongoDB database using the mongoose module. The following code will connect to the database.

const mongoose = require('mongoose');
const databaseURL = 'mongodb://127.0.0.1:27017/';
const databaseName = 'app';

mongoose.connect(databaseURL + databaseName, (error)=>{
    if(error){
        throw Error(error);
    }
});

mongoose.createConnection(databaseURL+databaseName, (error, result)=>{
    if(error){
        throw Error(error);
    }
    console.log('Connected to database ! ');
});

Here we have created a database app. We are connecting to our database listening on the port no 27017, which is the default port of MongoDB. The creteConnection has two parameters:

  • error - Contains the error message when failure else is null.
  • result - Contains the database object when connected to the database.

Schema of the database

Mongoose.Schema() is used to create the schema which defines the required documents and their data types. Suppose for a document field email. The data should be an email, for example, example@mail.com is a valid email however exam ple@email.com, example@email are invalid email data and cannot be inserted. So the schema can be defined by:

var schema = new Mongoose.Schema({
email: {
    type: String, // the datatype should be a string
    required: true, // must be provided by the user
    trim: true, // trim trailing and leading spaces
    validate(email){
        if(!!validator.isEmail(email)){     // if not a valid email
            throw Error('Not valid email') // throw error
        }
    }
}, 
password: {
    type: String,
    required: true,
    trim: true,
    minLength: [8, 'Password is too short'] 
    // if the provided password is less than 8 characters, 
    // than throw an Error - 'Password is too short'
}
})

Create Model

mongoose.model() will create the model. The first argument is the collection name and the second argument is the schema.

const User = mongoose.model('user', schema)

Insert Data

To insert data in the database, create an object of the model.

var user = User({
    email: 'asim@email.com',
    password: '12345678'
})

To insert the data use the save() method.

user.save().then(()=>{
    console.log('Data inserted!') // Will print in case of insertion
}).catch((error)=>{
    throw Error(error);
})

You can check by inserting invalid data.

Screenshot (113).png

Read Data

To read the data we use the find() or findOne(). The only difference is that the find() returns all the document matching the filter while findOne()returns only the first document matching the filter.

const filter = {
    email: 'asim@email.com'
}

    // {} - empty filter
    User.find({}).then((users)=>{
        console.log(users)
    })
    .catch((e)=>{
        throw Error(users)
    })

    User.findOne({filter}).then((users)=>{
        console.log(users)
    })
    .catch((e)=>{
        throw Error(users)
    })

Screenshot (116).png

Update data

Data can be updated by updateOne() and updateMany().

User.updateOne({email: 'email@email.com'}, {
    password: 'abcdefgh'
}).then((update)=>{
    console.log(update)
}) 
// Update atmost one document matching that filter

User.update({}).then((user)=>{
    console.log(user)
})
// Update all the documents matching the filter

Screenshot (115).png

Delete data

Data can be deleted by using deleteOne() and deleteMany().

User.deleteOne({email: 'email@emailcom'})
User.deleteMany({email: 'email1.com'})

Conclusion

In the following blogs we learnt to perform the operations:

  • Database is connected by using:

    • mongoose.connect(databaseURL/databaseName) and
    • mongoose.createConnection(databaseURL/databaseName)
  • MongoDB Schema is created using mongoose.Schema({})

  • Data Model is created using mongoose.Model(colelctionName, schema).
  • Operation performed:
    • insertion using Model.save(object).
    • read using Model.find(filter) and Model.findOne(filter)
    • updated using Model.updateOne(filter, value) and Model.updateMany(filter, value).
    • deletion using Model.deleteOne(filter) and Model.deleteMany(filter).