{{announcement.body}}
{{announcement.title}}

Using CRUD Operations in MongoDB in Node.js Using Mongoose

DZone 's Guide to

Using CRUD Operations in MongoDB in Node.js Using Mongoose

Take a look at how you can translate JSON data to the Mongoose schema language and then perform CRUD operations.

· Database Zone ·
Free Resource

MongoDB CRUD Operations

Mongoose provides a simple schema-based solution to model your app data. In this post, we will see how we can use it to write basic CRUD operations in Node.js.

Understanding Schema

First let's write a Mongoose schema for a sample requirement. Example entity is Team, where I want to save:

  • Team name
  • Team members and their roles
  • Who created this team
  • CreatedAt and UpdatedAt timestamps

JSON Data

First, let's take a look at how the JSON data will look:

JSON
 




x
18


 
1
{
2
  name: "My Super Team",
3
  createdBy: "adam@xyz.com",
4
  members: [
5
    {
6
      email: "adam@xyz.com",
7
      role: "admin"
8
    },
9
    {
10
      email: "james@xyz.com",
11
      role: "user"
12
    },
13
    {
14
      email: "steve@xyz.com",
15
      role: "admin"
16
    }
17
  ]
18
}


Let's write it in the Mongoose schema language.

C
 




xxxxxxxxxx
1
25


 
1
'use strict';
2
 
          
3
const mongoose = require('mongoose');
4
const Schema = mongoose.Schema;
5
const timestamps = require('mongoose-timestamp');
6
 
          
7
const TeamMemberSchema = new Schema({
8
    email: String,
9
    role: String
10
});
11
TeamMemberSchema.plugin(timestamps);
12
 
          
13
const TeamSchema = new Schema({
14
    name: String,
15
    createdBy: String,
16
    members: [TeamMemberSchema]
17
}, {
18
    w: 'majority',
19
    wtimeout: 10000,
20
    collation: { locale: 'en', strength: 1 }
21
});
22
 
          
23
TeamSchema.plugin(timestamps);
24
 
          
25
module.exports = mongoose.model('Team', TeamSchema);


The model above is self-explanatory. I have used a timestamp plugin for Mongoose, which will automatically put two fields:

  • createdAt
  • updatedAt

Also, I have used a nested schema in the above example. There is another important thing to see is that I have not defined the  _id field. Mongoose will automatically create this, if I have not mentioned it in my schema. I can also define how I would want my  _id  field to be generated.

Add New Record

C
 




xxxxxxxxxx
1
16


 
1
add(args) {
2
    if (!args.name || !args.email) {
3
        return Promise.reject(new Error('Paass team name and creator email'));
4
    }
5
    //using winston logging
6
    logger.log('info', 'Adding team', {name: args.name, createdBy: args.email});
7
 
          
8
    let obj = new Team();
9
    obj.name = args.name;
10
    obj.createdBy = args.email;
11
    obj.members = [{
12
        email: args.email,
13
        role: args.role
14
    }];
15
    return obj.save();
16
}


The above code is pretty simple. You can add more robust checks, and error conditions. You might want to set data in cache.

Update Record

There are several ways you can update your record, it all depends on your need. Let's see a few simple examples:

Simple Update of A Field

Say, we want to update the team name.

By loading complete object:

C
 




xxxxxxxxxx
1
11


 
1
updateTeam(teamId, teamName) {
2
  return Team.findById(teamId)
3
    .then(team => {
4
      if (!team) {
5
        return Promise.reject(new Error('Team not found'));
6
      }
7
      team.name = teamName;
8
      return team.save();
9
    });
10
  return Team.upate({_id: args.teamId}, {
11
}


By NOT loading complete object

C
 




xxxxxxxxxx
1


 
1
updateTeam(teamId, teamName) {
2
  return Team.upate({_id: args.teamId}, {
3
    name: teamName
4
  });
5
}


There are bunch of options to do update. You might want to see various options in Mongoose documentation.

Get a Record

C
 




xxxxxxxxxx
1


 
1
getById(teamId) {
2
  return Team.findById(teamId)
3
}


Delete Record

C
 




xxxxxxxxxx
1


 
1
delete(teamId) {
2
  return Team.deleteOne({_id: teamId})
3
}


The examples above are simple and easy to understand. Let me know if if you have some comments.

You might be also interested in MongoDB backup and Restore.

Topics:
crud operations ,database ,json ,mongo db ,mongoose mongodb ,nodejs

Published at DZone with permission of Gorav Singal . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}