DEV Community

Cover image for CRUD operations with mongoose models: a step-by-step guide
Okure U. Edet Kingsley🧑‍💻🚀
Okure U. Edet Kingsley🧑‍💻🚀

Posted on

CRUD operations with mongoose models: a step-by-step guide

Table of Contents

  • Introduction
  • What are CRUD operations?
  • Setting up MongoDB
  • Defining a mongoose model
  • CRUD operations with Mongoose models
  • Conclusion

Introduction

Recently, I started learning how to use MongoDB and I was hit with bugs when setting up MongoDB especially when it came to performing CRUD(create, read, update and delete) operations with Mongoose models. I was finally able to do so. I wrote this article to guide developers and those new to MongoDB on performing CRUD operations with Mongoose models. By the end of this article, you will be able to set up MongoDB, create a mongoose model and perform CRUD operations with the model. In short, this article will get you started on performing your own CRUD operations with Mongoose models.

What are CRUD operations?

CRUD stands for create, read, update and delete. Most software applications utilize some form of CRUD functionality. In MongoDB, data retrieved from a user is stored in a collection as a document. These documents can then be read, updated and even deleted. In this article, you will understand how these operations work in the context of a form.

Setting up MongoDB

Open your Chrome browser or any browser you currently use and navigate to this website: https://www.mongodb.com/. Hover over the Products link and click on community server. Select the platform you want to download MongoDB to. It may be Windows x64 or macOS x64. Once you are done with downloading and installing MongoDB, do not forget to download MongoDB compass.

Create a new directory for this project and run the following command in the terminal:

npm init -y
Enter fullscreen mode Exit fullscreen mode

This command will initialise a new node.js project. Once it is done, you should see a package.json file in your project directory.

After installing MongoDB and Mongo compass, go ahead and install mongoose:

npm install mongoose
Enter fullscreen mode Exit fullscreen mode
  • Creating a server

The server will be created using Express. So go ahead and install Express:

npm install express
Enter fullscreen mode Exit fullscreen mode

Inside your directory, create an index.js file. You can use a code editor to do this. Inside this file, add the following code:

const express = require('express')

const app = express();

app.listen(3000, function () {
  console.log("App listening on port 3000...");
});
Enter fullscreen mode Exit fullscreen mode

The above code imports express, stores it into an app variable and then starts the server at port 3000. You can of course use another port.

  • Connecting to MongoDB from node

Inside the index.js file, add the following code:

const mongoose = require('mongoose')

mongoose.connect("mongodb://localhost:27017/db", { useNewUrlParser: true });
Enter fullscreen mode Exit fullscreen mode

Mongoose is imported and used to establish a connection with the MongoDB database. The mongoose.connect method takes in a parameter and a database name. The name of the database we want to connect to is db. if this database does not exist, one will be created for us.

Defining a mongoose model

Inside your project directory, create another directory or folder called models. A model encloses a mongoose schema. A Mongoose schema is similar to a blueprint that defines the essential properties of a document. Inside this directory, create a file called User.js and add the following code:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  username: String,
  email: String,
});

const User = mongoose.model("User", UserSchema);

module.exports = User;
Enter fullscreen mode Exit fullscreen mode

A schema is created using the mongoose.Schema method. A schema of a document in a collection will look like. Once that is done, we access the database through the mongoose.model method. This method accepts a model name and the schema. Mongoose automatically creates a plural version of the model name. In our case, it will be Users instead of User as specified.

CRUD operations with Mongoose models

By now, you must have established a connection with MongoDB using mongoose. It is now time to illustrate CRUD(create, read, update and delete) operations using Mongoose.
In your root folder, create an example.js file and add the following code:

const mongoose = require("mongoose");
const User = require("./models/User");

mongoose.connect("mongodb://127.0.0.1:27017/db", { useNewUrlParser: true });

User.create({
  username: "Kingsley",
  email: "kingsley@gmail.com",
})
  .then(function (user) {
    console.log(user);
  })
  .catch(function (error) {
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode

The User model is first imported. Then a connection with MongoDB is established. Once that is done, we then use a method in the User model called create. This method allows us to create a new document in line with our schema. We log the User object to the console. To see if our code is working, open your terminal and execute example.js:

$ node example.js
Enter fullscreen mode Exit fullscreen mode

It should show something like this

{
  username: 'Kingsley',
  email: 'kingsley@gmail.com',
  _id: new ObjectId("64ef25aeaf83ce8e4d4fd786"),
  __v: 0
}
Enter fullscreen mode Exit fullscreen mode

It is important to note that every document in MongoDB has a unique _id as you can see in the _id property.

You can see the data created for you in MongoDB compass. Just open it up. It will look something like this:

Mongo compass

  • Reading data from MongoDB

If you want to retrieve one document in the User collection, use the .findOne() method. This method accepts two parameters: specification and projection. The former specifies the criteria used to find the documents. The latter determines which fields are returned.
For example:

User.findOne({ email: "kingsley@gmail.com" }, { username: 1 })
  .then((user) => {
    console.log(user);
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode
$ node example.js
{ _id: new ObjectId("64ef7f38d29a236158c77b62"), username: 'Kingsley' }
Enter fullscreen mode Exit fullscreen mode

Documents with the email kingsley@gmail.com are found and the username is returned.

You can also use the .find() method.

User.find()
  .then((user) => {
    console.log(user);
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode
$ node example.js
[
  {
    _id: new ObjectId("64ef7f38d29a236158c77b62"),
    username: 'Kingsley',
    email: 'kingsley@gmail.com',
    __v: 0
  }
]
Enter fullscreen mode Exit fullscreen mode

This finds all the documents in the User collection.

User.find({ username: /K/ })
  .then((user) => {
    console.log(user);
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode
$ node example.js
[
  {
    _id: new ObjectId("64ef7f38d29a236158c77b62"),
    username: 'Kingsley',
    email: 'kingsley@gmail.com',
    __v: 0
  }
]
Enter fullscreen mode Exit fullscreen mode

This finds all the documents that begin with K. Note that we used the //. It is similar to how it is used in a regular expression.

You can use the .findById() method:

const id = "64ef7f38d29a236158c77b62";
User.findById(id)
  .then((user) => {
    console.log(user);
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode
$ node example.js
{
  _id: new ObjectId("64ef7f38d29a236158c77b62"),
  username: 'Kingsley',
  email: 'kingsley@gmail.com',
  __v: 0
}
Enter fullscreen mode Exit fullscreen mode

This finds a document by its unique ID.
To get a full appraisal of methods that can be used to find a document, visit: https://www.mongodb.com/docs/manual/tutorial/query-documents/.

  • Updating data in MongoDB

To update a document in MongoDB is quite simple. You can use the .findByIdAndUpdate() method:

const id = "64ef7f38d29a236158c77b62";
User.findByIdAndUpdate(id, { email: "kingsleyokgeorge@gmail.com" })
  .then((user) => {
    console.log(user);
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode
$ node example.js
{
  _id: new ObjectId("64ef7f38d29a236158c77b62"),
  username: 'Kingsley',
  email: 'kingsleyokgeorge@gmail.com',
  __v: 0
}
Enter fullscreen mode Exit fullscreen mode

The email was updated to kingsleyokgeorge@gmail.com. Try it and see!

  • Deleting data from MongoDB
const id = "64ef7f38d29a236158c77b62";
User.findByIdAndDelete(id)
  .then((user) => {
    if (!user) {
      console.log("Deleted!");
    }
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode
$ node example.js
Deleted!
Enter fullscreen mode Exit fullscreen mode

If you check MongoDB compass, you will discover that there is no document in the User collection. It has been deleted.

Conclusion

Throughout this article, you have learned how to perform and simulate CRUD operations with Mongoose models. You have learned how to create, read, update and delete documents from a collection. You can apply what you have learned in this article to your side projects. For more information on Mongoose models and CRUD operations, refer to the docs: https://www.mongodb.com/docs/manual/crud/

Top comments (0)