Node and MongoDB with Mongoose

This post describes how to add MongoDB with Mongoose as a database to your Node application.

Interesting links

https://mongoosejs.com/
Part 3 of the Mozilla Express Tutorial
https://mongoosejs.com/docs/index.html
https://medium.freecodecamp.org/introduction-to-mongoose-for-mongodb-d2a7aa593c57
https://www.jenniferbland.com/saving-data-to-mongodb-database-from-node-js-application-tutorial/

Installing and starting MongoDB

First install MongoDB on your system. For MacOS the instructions are available on the MongoDB homepage.
brew update
brew install mongodb
The MongoDB daemon that executes the database is started with:
/usr/local/bin/mongod --config /usr/local/etc/mongod.conf

The mongo shell

The mongo shell is a command line tool that allows you to connect to the mongodb and perform queries. It will connect to mongodb://127.0.0.1:27017 if no parameters are specified

/usr/local/bin/mongo

To display the database you are using, type db
To switch databases, issue the use <db> command
To show all databases that contain at least one document, type show dbs
To show all collections in a database, type show collections

MongoDB is case sensitive! The schema passwordentry is a different schema than PasswordEntry!

Inserting:

db.PasswordEntry.insertOne( { password: "test" } )

Select all entries:

db.PasswordEntry.find ( {} )

Using MongoDB from within Node

To install the mongoose npm dependency and a JSON middleware type

npm install mongoose
npm install body-parser save

MongoDB is a NoSQL Database that deals with documents that are stored in so called collections. The synonym for a collection is a table. The synonym for a record in a table is a document.

The fields of a document are defined using a schema. Given a schema, you can create a model. A model is a factory that creates documents which then are saved into collections.

Because models can only be defined once (otherwise an exception is thrown) in the application lifecycle (You can update them several times to add more fields, but you can create them only once), you need some centralized code that defines the schema and then creates the models.

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/crypto");

// define a schema
var passwordEntrySchema = new mongoose.Schema({
  password: { type: String, required: true }
});

// this adjusts the conversion of mongoose objects to json when serializing the objects
// it outputs the _id as id and removes the _id. It also removes the __v field.s
passwordEntrySchema.set('toJSON', {
  transform: function (doc, ret, options) {
    ret.id = ret._id;
    delete ret._id;
    delete ret.__v;
  }
});

// compile the schema into a model
let collectionName = 'peCollection';

// create and export the model
// models can only be created once, that is why this code is put into its own module
module.exports = mongoose.model('PasswordEntry', passwordEntrySchema, collectionName);

Once you have that centralized module, you can import the model into other places. Here is how to create a document and save it:

var express = require('express');
var router = express.Router();

const mongoose = require('mongoose');
var PasswordEntryModel = require('../mongo/mongo.js');

router.post('/add', function (req, res, next) {

  console.log('/add ', req.body);

  var myData = new PasswordEntryModel(req.body);
  myData.save()
    .then(item => {
      res.send("item saved to database");
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });

  console.log('/add end');
});

module.exports = router;

It is assumed, that a JSON describing a PasswordEntryModel is posted to this router.

Leave a Reply