How to use the ODM mongoose with your db

Have a Database Problem? Speak with an Expert for Free
Get Started >>

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.

1
npm init -y

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

1
npm install express

The last step here is to install mongoose.

1
npm install mongoose

We also need nodeman to run the server.

1
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.

1
2
3
{
  collection: "employees";
}

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

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

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

1
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.

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

Next, we need an instance of express.

1
const app = express();

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

1
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.

1
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.

1
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.

1
2
3
4
5
6
7
8
9
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.

1
nodemon server

Image from Gyazo

Inserting data

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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.