Set Up Mongoose with MongoDB and NodeJS
Overview of Mongoose
Mongoose is an ODM (Object Data Modeling) library layered on top of the MongoDB driver. It provides a neat, streamlined way to work with MongoDB and supports easy object modeling in a NodeJS environment.
Prerequisites
Before you start, you should ideally:
- Set up a non-root user with sudo permissions.
- Make sure your server is fully updated.
- Check that build-essential is installed. If it is missing, install it with:
$ sudo apt install build-essential
1. MongoDB
Install MongoDB.
$ sudo apt install mongodb
Confirm the installation is working. In the status output, you should see “active (running)”.
$ sudo systemctl status mongodb
Active: active (running)
2. NodeJS and NPM
Add the most recent stable NodeJS repository.
$ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
Install NodeJS.
$ sudo apt install nodejs
Check that both NodeJS and NPM are installed correctly.
$ node -v && npm -v
v12.x.x
6.x.x
3. Initialize the Mongoose Project
Create the main directory for your project.
$ cd ~
$ mkdir mongooseProject && cd mongooseProject
Initialize a NodeJS development setup so that package.json is created automatically:
$ npm init
Answer the short setup questions based on your project needs. For example, if you just press return each time to accept defaults, npm init will respond with something like:
About to write to /root/mongooseProject/package.json:
{
"name": "mongooseproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
From the project root, install the required packages with npm:
$ npm install --save mongoose
4. Define a Model
Create a folder named Models in the project root, then move into it:
$ cd ~/mongooseProject
$ mkdir Models && cd Models
Create connectDB.js. This file will include the connection logic for your MongoDB server.
$ nano connectDB.js
Paste the following into connectDB.js.
const mongoose = require('mongoose'); // Import mongoose library
module.exports = function(uri) {
mongoose.connect(uri, { //attempt to connect to database
useNewUrlParser: true, // Recommended, insures support for future MongoDB drivers
useUnifiedTopology: true // Recommended, uses new MongoDB topology engine
}).catch(error => console.log(error)) // Error handling
mongoose.connection.on('connected', function () { // On connection
console.log('Successful connection with database: ' + uri); // Callback for successful connection
});
}
Create Users.js. This file will contain the model for the Users database collection.
$ nano Users.js
Insert the following into Users.js to define a basic schema for users.
const mongoose = require("mongoose"); // Import mongoose library
const Schema = mongoose.Schema // Define Schema method
// Schema
var UsersSchema = new Schema({ // Create Schema
name: String, // Name of user
age: Number, // Age of user
role: String // Role of user
})
// Model
var Users = mongoose.model("Users", UsersSchema) // Create collection model from schema
module.exports = Users // export model
5. Insert Documents into MongoDB
Create insertUser.js in the project’s root directory.
$ cd ~/mongooseProject
$ nano insertUser.js
Paste the following into insertUser.js. This script inserts documents into the Users collection.
//Library
const mongoose = require("mongoose")
// Database connection
const connectDB = require("./Models/connectDB")
var database = "mongoose" // Database name
// Models
const Users = require("./Models/Users")
// Connect to database
connectDB("mongodb://localhost:27017/"+database)
var insertedUser = new Users({ // Create new document
name: "John Doe",
age: 18,
role: "Example User"
})
insertedUser.save(err => { // save document inside Users collection
if(err) throw err // error handling
console.log("Document inserted!")
mongoose.disconnect() // disconnect connection from database once document is saved
})
Run insertUser.js.
$ node insertUser.js
Successful connection with database: mongodb://localhost:27017/mongoose
Document inserted!
6. Read Documents from MongoDB
Create readUsers.js in the root of the project.
$ cd ~/mongooseProject
$ nano readUsers.js
Add the following content to readUsers.js. This script reads documents from the Users collection.
//Library
const mongoose = require("mongoose")
// Database connection
const connectDB = require("./Models/connectDB")
var database = "mongoose" // Database name
// Models
const Users = require("./Models/Users")
// Connect to database
connectDB("mongodb://localhost:27017/"+database)
Users.find({}, (err, users)=>{ //find and return all documents inside Users collection
if(err) throw err // error handling
console.log(users)
mongoose.disconnect()
})
Execute readUsers.js. The result will be an array of objects.
$ node readUsers.js
Successful connection with database: mongodb://localhost:27017/mongoose
[ { _id: ************************,
name: 'John Doe',
age: 18,
role: 'Example User',
__v: 0 } ]
Conclusion
You have set up Mongoose to work with MongoDB. For further details, consult the Mongoose API documentation.
Set Up Mongoose with MongoDB and NodeJS
Overview of Mongoose
Mongoose is an ODM (Object Data Modeling) library layered on top of the MongoDB driver. It provides a neat, streamlined way to work with MongoDB and supports easy object modeling in a NodeJS environment.
Prerequisites
Before you start, you should ideally:
- Set up a non-root user with sudo permissions.
- Make sure your server is fully updated.
- Check that build-essential is installed. If it is missing, install it with:
$ sudo apt install build-essential
1. MongoDB
Install MongoDB.
$ sudo apt install mongodb
Confirm the installation is working. In the status output, you should see “active (running)”.
$ sudo systemctl status mongodb
Active: active (running)
2. NodeJS and NPM
Add the most recent stable NodeJS repository.
$ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
Install NodeJS.
$ sudo apt install nodejs
Check that both NodeJS and NPM are installed correctly.
$ node -v && npm -v
v12.x.x
6.x.x
3. Initialize the Mongoose Project
Create the main directory for your project.
$ cd ~
$ mkdir mongooseProject && cd mongooseProject
Initialize a NodeJS development setup so that package.json is created automatically:
$ npm init
Answer the short setup questions based on your project needs. For example, if you just press return each time to accept defaults, npm init will respond with something like:
About to write to /root/mongooseProject/package.json:
{
"name": "mongooseproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
From the project root, install the required packages with npm:
$ npm install --save mongoose
4. Define a Model
Create a folder named Models in the project root, then move into it:
$ cd ~/mongooseProject
$ mkdir Models && cd Models
Create connectDB.js. This file will include the connection logic for your MongoDB server.
$ nano connectDB.js
Paste the following into connectDB.js.
const mongoose = require('mongoose'); // Import mongoose library
module.exports = function(uri) {
mongoose.connect(uri, { //attempt to connect to database
useNewUrlParser: true, // Recommended, insures support for future MongoDB drivers
useUnifiedTopology: true // Recommended, uses new MongoDB topology engine
}).catch(error => console.log(error)) // Error handling
mongoose.connection.on('connected', function () { // On connection
console.log('Successful connection with database: ' + uri); // Callback for successful connection
});
}
Create Users.js. This file will contain the model for the Users database collection.
$ nano Users.js
Insert the following into Users.js to define a basic schema for users.
const mongoose = require("mongoose"); // Import mongoose library
const Schema = mongoose.Schema // Define Schema method
// Schema
var UsersSchema = new Schema({ // Create Schema
name: String, // Name of user
age: Number, // Age of user
role: String // Role of user
})
// Model
var Users = mongoose.model("Users", UsersSchema) // Create collection model from schema
module.exports = Users // export model
5. Insert Documents into MongoDB
Create insertUser.js in the project’s root directory.
$ cd ~/mongooseProject
$ nano insertUser.js
Paste the following into insertUser.js. This script inserts documents into the Users collection.
//Library
const mongoose = require("mongoose")
// Database connection
const connectDB = require("./Models/connectDB")
var database = "mongoose" // Database name
// Models
const Users = require("./Models/Users")
// Connect to database
connectDB("mongodb://localhost:27017/"+database)
var insertedUser = new Users({ // Create new document
name: "John Doe",
age: 18,
role: "Example User"
})
insertedUser.save(err => { // save document inside Users collection
if(err) throw err // error handling
console.log("Document inserted!")
mongoose.disconnect() // disconnect connection from database once document is saved
})
Run insertUser.js.
$ node insertUser.js
Successful connection with database: mongodb://localhost:27017/mongoose
Document inserted!
6. Read Documents from MongoDB
Create readUsers.js in the root of the project.
$ cd ~/mongooseProject
$ nano readUsers.js
Add the following content to readUsers.js. This script reads documents from the Users collection.
//Library
const mongoose = require("mongoose")
// Database connection
const connectDB = require("./Models/connectDB")
var database = "mongoose" // Database name
// Models
const Users = require("./Models/Users")
// Connect to database
connectDB("mongodb://localhost:27017/"+database)
Users.find({}, (err, users)=>{ //find and return all documents inside Users collection
if(err) throw err // error handling
console.log(users)
mongoose.disconnect()
})
Execute readUsers.js. The result will be an array of objects.
$ node readUsers.js
Successful connection with database: mongodb://localhost:27017/mongoose
[ { _id: ************************,
name: 'John Doe',
age: 18,
role: 'Example User',
__v: 0 } ]
Conclusion
You have set up Mongoose to work with MongoDB. For further details, consult the Mongoose API documentation.


