Mongoose allows us to easily access MongoDB commands for CRUD. There is always a need to create, read, update, and delete information all the time. CRUD is the most necessary thing out there to do so.

Topics Covered

  • Initial steps to follow while working on mongoose
  • Defining Schema and Model
  • Inserting data into Database
  • Query the Database
    • Read
    • Update
    • Delete

Initial steps to follow while working on mongoose

Step 1: Be sure you have MongoDB and Node.js installed.

Step 2: Install Mongoose from the command line.

$ npm install mongoose --save

Step 3: Include mongoose in our project.

var mongoose = require('mongoose');

Step 4: Connect to a MongoDB database.

mongoose.connect('mongodb://localhost/test');

Step 5: We have a pending connection to the test database running on localhost. Now to check the pending connection:

mongoose.connection.on('connected', function () {
    console.log("mongoose connection ready" + url);
});
mongoose.connection.on('error', function () {
    console.log("mongoose connection error" + url);
});
mongoose.connection.on('disconnected', function () {
    console.log("mongoose connection disconnected" + url);
});

Defining Schema and Model

Step 6: Define mongoose Model and Schema.

In Mongoose, everything is derived from a Schema.

var testSchema = mongoose.Schema({
    name: String,
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    admin: Boolean
});

A schema with properties name, username, password, and admin. Which will be of types string, string, string and boolean respectively.

SchemaTypes in mongoose :

  • String
  • Number
  • DateBuffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

Compiling our schema into a Model

var Test = mongoose.model('Test', testSchema, 'collection_name');

 A combined sample with both schema and model

//require mongoose
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var TestSchema = Schema({

    name: String,
    username: {
        type: String,
        required: true,
        unique: true
    },
    password:
        {
            type: String,
            required: true
        },
    admin: Boolean
});

// the schema is useless, we need to create a model using it
var Test= mongoose.model('Test', TestSchema, 'collection_name');

// make this available to our users in our Node applications
module.exports = Test;

Inserting data into Database

We still haven’t saved anything to MongoDB. To save the Test and data we had created earlier, we need to use a built-in method Create on mongoose Model.

Create

// grab the test model
var Test = mongoose.model('Test');

// create a JSON data
var data = {
    name: 'newuser',
    username: 'user',
    password: 'password',
    admin: true
};

// create data using test we have created in the model
Test
    .create(data, function (err, result) {
        if (err) throw err;
        console.log('Test created!');
    });

Query the Database

Following are few examples, to query the database that we have created :

Read

// get all the data from test
Test
    .find({}, function (err, data) {
        if (err) throw err;

        // object of all the test
        console.log(data);
    });

Find One :

// get newuser from model test
Test
    .find({ username: 'newuser' }, function (err, data) {
        if (err) throw err;

        // object of the test
        console.log(data);
    });

Find By ID :

// get the test with ID of 1
Test
    .findById(1, function (err, data) {
        if (err) throw err;

        // show the test with ID of 1
        console.log(data);
    });

Update

Find a specific data from test and modify that particular attribute.

Find By Id and Update :

// find test with id 3
// update username to admin
Test
    .findByIdAndUpdate(3, { username: 'admin' }, function (err, data) {
        if (err) throw err;

        // we have the updated data returned to us
        console.log(data);
    });

Find and Update :

// find test newuser
// update him to admin
Test
    .findOneAndUpdate({ username: 'newuser' }, { username: 'admin' }, function (err, data) {
        if (err) throw err;

        // we have the updated data returned to us
        console.log(data);
    });

Delete

Find By ID and Remove :

// find the test with id 4 and remove
Test
    .findByIdAndRemove(4, function (err) {
        if (err) throw err;

        // we have deleted the user
        console.log('data deleted!');
    });

Find and Remove :

// find test where username is admin and remove
Test
    .findOneAndRemove({ username: 'admin' }, function (err) {
        if (err) throw err;

        // we have deleted the user
        console.log('data deleted!');
    });

Learn More: