How to use the ODM mongoose with your db

Introduction

MongoDB is one of the most popular NoSQL databases. It stores data in BSON format (an extension of JSON). It is faster than SQL databases and handles unstructured data very efficiently. MongoDB is often used with NodeJS. Node.js is a javascript runtime environment that executes javascript outside the browser. Both MongoDB and Node.js are important parts of MEAN and MERN stack. We need object mapping between MongoDB and NodeJS. For this we use Mongoose.

Mongoose is an Object Data Modeling library. It provides schema validation and manages relationships between data. It is used to translate between objects in code and the representation of those objects in MongoDB. In this article, we will discuss how to use the ODM mongoose with your db.

Installing express and mongoose

The first step is to install some necessary packages. Create a new folder and name it whatever you like. Then open a terminal and move to the newly created folder. We need a package.json file to start. Run the following command to create a package.json file.

npm init -y

The next step is to install express. Express will provide all the necessary node modules.

npm install express

The last step here is to install mongoose.

npm install mongoose

We also need nodeman to run the server.

npm install -g nodemon

Setting up the schema and model

MongoDB is a schema-less database. We will use mongoose to create a schema in a separate file(model.js). Then we will create a model that takes a schema and create an instance of a document.

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

let employee = new Schema(
  {
    name: {
      type: String
    },
    age: {
      type: Number
    },
    location: {
      type: String
    }
  },
  { collection: "employees" }
);

The schema defines how each document in the collection will look. There will be three fields in each document – name, age, and location. We also specified the collection name in the schema.

{
  collection: "employees";
}

Now, we can call the model constructor and pass the collection name as well as a reference to the schema definition.

module.exports = mongoose.model("Employees", employee);

We have to import it in the server.js file.

var employees = require("./model.js");

Connection with MongoDB

Let’s connect with the database.

In the same folder, create a new file and name it “server.js”. This will be the starting point of the application. Let’s import express and mongoose.

var mongoose = require("mongoose");
const express = require("express");

Next, we need an instance of express.

const app = express();

The model we created earlier is also needed in this file. Let’s import it.

var employees = require("./model.js");

Now pay attention to the next step. It is the most important part. We need the URI that will specify the database in the localhost.

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

Here, ‘127.0.0.1’ is the localhost and ‘27017’ is the default port on which MongoDB runs. ‘details’ is the name of the database.

Finally, we can connect to MongoDB using the connect() method. The URI we created will be the first parameter of this method.

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

The second parameter is an object to avoid warnings.

The final step is to create a connection and run the server on a port.

const connection = mongoose.connection;

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

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

This is how server.js looks.

var mongoose = require("mongoose");
const express = require("express");
const app = express();
var employees = require("./model.js");
var uri = "mongodb://127.0.0.1:27017/details";
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });

const connection = mongoose.connection;

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

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

Let run the server using nodemon.

nodemon server

Image from Gyazo

Inserting data

So the server is working. Now we can insert the following documents in the collection.

var docs = [
  {
    name: "John",
    age: 21,
    location: "New York"
  },
  {
    name: "Sam",
    age: 27,
    location: "Texas"
  },
  {
    name: "Lisa",
    age: 23,
    location: "Chicago"
  }
];

The following route handle will insert data in the collection. We will use the insertMany() method.

router.route('/insertData').post(function(req,res){

employees.insertMany(, function(err, result){
if(err)
{
res.send(err)
}
else{
res.send(result)
}
})

})

We also need to insert a router instance in the file. This is how the final server.js looks.

var mongoose = require('mongoose')
const express = require('express')
const app = express()
var employees = require('./model.js')
var uri = 'mongodb://127.0.0.1:27017/details'
const router = express.Router()
mongoose.connect(uri,{ useUnifiedTopology: true, useNewUrlParser: true})

const connection = mongoose.connection

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

router.route('/insertData').post(function(req,res){

employees.insertMany(, function(err, result){
if(err)
{
res.send(err)
}
else{
res.send(result)
}
})

})
app.use('/', router)
app.listen(4000, function() {
console.log("Server is running on Port: 4000")
})

Let’s execute the route handler using the postman tool. You can download the postman tool from www.getpostman.com.

Image from Gyazo

Yes, documents are inserted successfully.

Conclusion

Thank you for reading this article about how to use the ODM mongoose with your MongoDB database. We hope it was a good practical example to learn from.

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.