nodejs|May 06, 2020|2 min read

Mongoose - Using CRUD operations in mongodb in nodejs

TL;DR

Use Mongoose schemas and models to perform create, read, update, and delete operations on MongoDB collections from Node.js with a clean schema-based approach.

Mongoose - Using CRUD operations in mongodb in nodejs

MongoDB CRUD Operations

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

Understanding Schema

First lets write a mongoose schema for a sample requirement. Example entity is Team, where I want to save:

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

JSON data

First lets take a look on how the JSON data will look like:

{
  name: "My Super Team",
  createdBy: "[email protected]",
  members: [
    {
      email: "[email protected]",
      role: "admin"
    },
    {
      email: "[email protected]",
      role: "user"
    },
    {
      email: "[email protected]",
      role: "admin"
    }
  ]
}

Lets write it in mongoose schema language.

'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const timestamps = require('mongoose-timestamp');

const TeamMemberSchema = new Schema({
    email: String,
    role: String
});
TeamMemberSchema.plugin(timestamps);

const TeamSchema = new Schema({
    name: String,
    createdBy: String,
    members: [TeamMemberSchema]
}, {
    w: 'majority',
    wtimeout: 10000,
    collation: { locale: 'en', strength: 1 }
});

TeamSchema.plugin(timestamps);

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 above example. There is another important thing to see is that I have not defined _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

add(args) {
    if (!args.name || !args.email) {
        return Promise.reject(new Error('Paass team name and creator email'));
    }
    //using winston logging
    logger.log('info', 'Adding team', {name: args.name, createdBy: args.email});

    let obj = new Team();
    obj.name = args.name;
    obj.createdBy = args.email;
    obj.members = [{
        email: args.email,
        role: args.role
    }];
    return obj.save();
}

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. Lets see few simple examples:

Simple update of a field

Say, we want to update team name.

By loading complete object

updateTeam(teamId, teamName) {
  return Team.findById(teamId)
    .then(team => {
      if (!team) {
        return Promise.reject(new Error('Team not found'));
      }
      team.name = teamName;
      return team.save();
    });
  return Team.upate({_id: args.teamId}, {
}

By NOT loading complete object

updateTeam(teamId, teamName) {
  return Team.upate({_id: args.teamId}, {
    name: teamName
  });
}

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

Get a Record

getById(teamId) {
  return Team.findById(teamId)
}

Delete Record

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

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

Related Posts

Nodejs - Json object schema validation with Joi

Nodejs - Json object schema validation with Joi

Introduction In this post, I will show how to validate your json schema…

How to check whether a website link has your URL backlink or not - NodeJs implementation

How to check whether a website link has your URL backlink or not - NodeJs implementation

Introduction I got my seo backlink work done from a freelancer. It was like 300…

How to connect to mysql from nodejs, with ES6 promise

How to connect to mysql from nodejs, with ES6 promise

Introduction I had to develop a small automation to query some old mysql data…

Nodejs with MongoDB - Number of Opened Connections Keep on Increasing with Mongoose Library

Nodejs with MongoDB - Number of Opened Connections Keep on Increasing with Mongoose Library

Introduction In one of my app, I was using to talk to . I have used some event…

How to Download multiple Youtube Videos using Nodejs and Show a Progress Bar

How to Download multiple Youtube Videos using Nodejs and Show a Progress Bar

Introduction I was trying to download some youtube videos for my kids. As I have…

Moment.js - How to perform date relatedd arithmetic in javascript/NodeJs

Moment.js - How to perform date relatedd arithmetic in javascript/NodeJs

Introduction In your backend and frontend projects, you always need to deal with…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…