Insert a Document into MongoDB Using Mongoose – Quick Guide

Insert Document Into MongoDB Using Mongoose Featured Image

In this tutorial, I will walk you through how to insert a document into MongoDB using Mongoose and get the generated ID out of it.

Most of the time you want to insert a document into your MongoDB database using and want to extract the ID (_id) to maybe use somewhere. This tutorial aims to walk you through a detailed yet easiest way to achieve this. Let us get started.

How to Insert a Document into MongoDB using Mongoose and Get the Generated ID?

To start off, you must have created your Node.js application. This guide also assumes you have installed MongoDB on your machine. If not, refer to this guide to install MongoDB on a Windows machine. We will then begin with installing all the required packages and start off with inserting a document.

In this guide, I will show you two methods to insert a document into MongoDB using Mongoose and get the generated ID. In the first one, we simply render the generated ID in the terminal. In the second method, I will demonstrate how you can render it on a webpage rather.

Steps to Insert a Document into MongoDB and Get the Generated ID in the Terminal

Follow the steps below to get started. Let us use an example of a drone store.

  • Install the Mongoose and Express packages:
npm i mongoose express
  • Using mongoose packages in the index.js file:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
  • Connect to the MongoDB local server with the help of Mongoose by passing this code:
mongoose.connect('mongodb://localhost:27017/droneStore', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log(`CONNECTED TO MONGO!`);
    })
    .catch((err) => {
        console.log(`OH NO! MONGO CONNECTION ERROR!`);
        console.log(err);
    })
  • Now, create a models folder in your project directory
  • Inside the models folder we will store our products model. I will name my first model product.js
  • Use the mongoose module by using require() in product.js.
  • Create a schema for your products. I have created them as such:
const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true,
        min: 0
    },
    utility: {
        type: [String],
        enum: ['Monitoring or Inspection', 'Security', 'Delivery', 'Photography', 'Recreation']
    },
    weight: {
        type: String,
        lowercase: true
    },
    onSale: {
        type: Boolean,
        default: false
    }
})
  • Next, create a model for product in product.js. This shall be a drone.
const Drone = mongoose.model('Drone', productSchema);
  • Now in the same file, just below the above lines of code, let us create a new product in our database, like this:
const drone = new Drone({
    name: "SV - Aira 157B",
    price: 2455,
    utility: ["Photography"],
    weight: "467 grams",
    onSale: False
})
  • Now that we have created our first product, it is not stored in the MongoDB database yet. To finally insert a document into MongoDB using Mongoose and get the generated ID, we need pass the following lines of code:
drone.save(function (err, doc) {
    console.log(doc._id);
});
  • Finally, make sure your MongoDB server is running. Run your Node.js app server like this:
node index.js

The output:

CONNECTED TO MONGO!
614e2ebf1bec592c88e1cd5b

Steps to Get the Generated ID on a Webpage

For this method, you only need to tweak and add a few lines of code. Follow the steps below to start.

  1. Firstly, comment out the lines of code that creates and inserts a document. We don’t the outputs to clash as we will log the output of this method on a webpage as well as the console.
// const drone = new Drone({
//     name: "SV - Aira 157B",
//     price: 2455,
//     utility: ["Photography"],
//     weight: "467 grams",
//     onSale: false
// })

// drone.save(function (err, doc) {
//     console.log(doc._id);
// })
  • Next, we will need to export our Drone model to make it usable in the index.js file. We will do this by making use of the export module in Node.js:
module.exports = Drone;
  • Switch to the index.js file or whatever you have named your app entry point file. Here, you will first need to import the Drone model using the require module. We will also need a port for our server to listen
const Drone = require('./models/product.js');
app.listen(3000, () => {
    console.log('Connected to PORT 3000...');
}) // Make sure this resides in the far end of the file
  • Now, let us create a GET request route and render the ID on a webpage:
app.get('/dronesid/:id', async (req, res) => {
    const { id } = req.params;
    const foundDrone = await Drone.findById(id);
    res.send(foundDrone._id)
})
  • Let us now start our Node.js application.
  • Once you have done that, jump to your browser and visit the route you created:

http://localhost:3000/dronesid/6034fd2bf74cfd0438bdb19b

We can simply paste the generated ID by copying it from the console or the database to check whether it’s working.

Here’s what our webpage looks like:

Insert A Document Into MongoDB Using Mongoose Webpage Output

This is what our console looks like:

Connected to PORT 3000...
CONNECTED TO MONGO!
6034fd2bf74cfd0438bdb19b

You can ignore deprecation warnings if any.

Conclusion

This tutorial demonstrates how to insert a document into MongoDB using Mongoose and get the generated ID both and print them in the console and on a webpage.

Noteworthy References

StackOverflow