Tutorials  /  JavaScript

Set Up Mongoose with MongoDB on a NodeJS Server

Ccentron Redaktion · December 2025 ·8 min read ·JavaScript, Tutorial

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.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

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:
Console
$ sudo apt install build-essential

1. MongoDB

Install MongoDB.

Console
$ sudo apt install mongodb

Confirm the installation is working. In the status output, you should see “active (running)”.

Console
$ sudo systemctl status mongodb
Active: active (running)

2. NodeJS and NPM

Add the most recent stable NodeJS repository.

Console
$ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

Install NodeJS.

Console
$ sudo apt install nodejs

Check that both NodeJS and NPM are installed correctly.

Console
$ node -v && npm -v
v12.x.x
6.x.x

3. Initialize the Mongoose Project

Create the main directory for your project.

Console
$ cd ~
$ mkdir mongooseProject && cd mongooseProject

Initialize a NodeJS development setup so that package.json is created automatically:

Console
$ 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:

Code
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:

Console
$ npm install --save mongoose

4. Define a Model

Create a folder named Models in the project root, then move into it:

Console
$ cd ~/mongooseProject
$ mkdir Models && cd Models

Create connectDB.js. This file will include the connection logic for your MongoDB server.

Console
$ nano connectDB.js

Paste the following into connectDB.js.

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

Console
$ nano Users.js

Insert the following into Users.js to define a basic schema for users.

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

Console
$ cd ~/mongooseProject
$ nano insertUser.js

Paste the following into insertUser.js. This script inserts documents into the Users collection.

JavaScript
//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.

Console
$ 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.

Console
$ cd ~/mongooseProject
$ nano readUsers.js

Add the following content to readUsers.js. This script reads documents from the Users collection.

JavaScript
//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.

Console
$ 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.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren