Use Mongoose with MongoDB in Ubuntu 19.10
Introduction
Mongoose is an ODM (Object Data Modeling) library built on top of the MongoDB driver. It allows for concise interaction with MongoDB and simple object modeling within a NodeJS environment.
Prerequisites
Before starting, it is recommended that you:
Set up a non-root user with
sudo
privileges. Follow Vultr's best practice guide here.Verify your server is up to date. Follow Vultr's best practice guide here.
Make sure
build-essential
is installed. If not, install using:$ sudo apt install build-essential
1. MongoDB
Install MongoDB.
$ sudo apt install mongodb
Verify it was installed properly. Look for "active (running)" in the output.
$ sudo systemctl status mongodb
Active: active (running)
2. NodeJS and NPM
Add the latest stable NodeJS repository.
$ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
Install NodeJS.
$ sudo apt install nodejs
Verify NodeJS and NPM are installed properly.
$ node -v && npm -v
v12.x.x
6.x.x
3. Initialize the Mongoose Project
Create the project root directory.
$ cd ~
$ mkdir mongooseProject && cd mongooseProject
Initialize a NodeJS development environment to automatically generate a package.json:
$ npm init
Answer the short questions to fit your project. For example, if you press return at each question to accept the defaults, the npm init process responds:
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"
}
Install the required packages using npm
in the project root directory:
$ npm install --save mongoose
4. Define a Model
Create a folder called Models in the root directory of the project and cd
into it:
$ cd ~/mongooseProject
$ mkdir Models && cd Models
Create connectDB.js. This file will contain the connection logic needed for the 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 database collection Users.
$ nano Users.js
Paste the following into Users.js. This defines 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 root directory of the project.
$ cd ~/mongooseProject
$ nano insertUser.js
Paste the following into insertUser.js file. This file 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 directory of the project.
$ cd ~/mongooseProject
$ nano readUsers.js
Paste the following into readUsers.js. This file reads documents in 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()
})
Run readUsers.js. The output is 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 more information, please see the Mongoose API documentation