Inserting data into MongoDB using post in mongoose

CRUD operations

As we all know, a database is used to store data. But it’s not just that. We always don’t have static data. After setting up a database, we may need to perform many operations. We may need to add more data, or we need all the data or some data. We may also need to update the data or even remove the data. These are the CRUD operations. It is an acronym that stands for Create, Read, Update, and Delete. Each kind of database has its own ways of performing CRUD operations.

Data can be inserted initially into a database during its creation. But it is common to insert data afterward also. A user may enter some data from the client-side and then that the entered data should be entered properly in the correct database. The Create operation inserts data in a database. We have to make a post request for such insertions. In this article, we will discuss how to insert data into a database using the post in mongoose.

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

Creating a server and establishing a connection with MongoDB

We will insert data into the kennel collection. Currently, there is no document in the kennel collection. First, we need to create a server and we also need a connection with the MongoDB database.

We will create the server using express and the connection can be set up by using mongoose.

var mongoose = require("mongoose");
const express = require("express");
const app = express();
var port = 4000;

var uri = "mongodb://127.0.0.1:27017/kennel";

mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });

const connection = mongoose.connection;

connection.once("open", function() {
  console.log("MongoDB database connection established successfully");
});

app.listen(port, function() {
  console.log("Server is running on Port: " + port);
});

Let’s run it using nodemon. You can install the nodemon using the following command.

npm install nodemon

Image from Gyazo

The server is running properly and connection with MongoDB is also established successfully.

Creating a schema

The next step is to create a schema.

Create a new file “model.js” add the following code in it.

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

let detail = new Schema({
  name: {
    type: String
  },
  age: {
    type: Number
  },

  breed: {
    type: String
  }
});

module.exports = mongoose.model("detail", detail);

The model is ready. We need to import this schema in the file where we created the server. Add the following line of code in that file.

let detail = require("./model");

Insert data using the post method

Before implementing the post method, we need a router. We can create a route using the express.

const app = express();
const router = express.Router();

The router is created and now we can use it in our application.

app.use("/", router);

With the help of the router, we can create a route handler.

router.route("/insertdata").post(function(req, res) {});

Have a look at the above route handler. The route() method is used. The parameter of the route() method is an endpoint. In our case, it is ‘/fetch’. The POST method is attached to it. The POST method has one parameter – a callback function. This callback function, in turn, has two parameters – request and response.

This is how a POST request is made in mongoose. But currently, this will do nothing. We have to use one of the methods provided by mongoose to insert data into the database. In our case, we will use the insertMany() method to insert three documents.

router.route("/insertdata").post(function(req, res) {
  kennel.insertMany(
    [
      { name: "Scooby" },
      { age: 5 },
      { breed: "Great Dane" },
      { name: "Rambo" },
      { age: 2 },
      { breed: "Pitbull" },
      { name: "Johny boy" },
      { age: 3 },
      { breed: "German Shephard" }
    ],
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

Let’s execute this route using the postman tool.

Image from Gyazo

The insertMany() method returns the documents that were added to the collection. This is how we use the post method to insert data in mongoose.

Conclusion

Thank you for joining us on another Object Rocket knowledge-base tutorial. We have covered how to use post in mongoose to insert data into your MongoDB database. If you have any questions, concerns, or need any database help please don’t hesitate to reach out to us.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.