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.
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:
$ sudo apt install build-essential1. MongoDB
Install MongoDB.
$ sudo apt install mongodbConfirm 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 nodejsCheck that both NodeJS and NPM are installed correctly.
$ node -v && npm -v
v12.x.x
6.x.x3. Initialize the Mongoose Project
Create the main directory for your project.
$ cd ~
$ mkdir mongooseProject && cd mongooseProjectInitialize a NodeJS development setup so that package.json is created automatically:
$ npm initAnswer 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 mongoose4. Define a Model
Create a folder named Models in the project root, then move into it:
$ cd ~/mongooseProject
$ mkdir Models && cd ModelsCreate connectDB.js. This file will include the connection logic for your MongoDB server.
$ nano connectDB.jsPaste 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.jsInsert 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 model5. Insert Documents into MongoDB
Create insertUser.js in the project’s root directory.
$ cd ~/mongooseProject
$ nano insertUser.jsPaste 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.jsAdd 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.
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.