Mongoose ORM basic usage

Mongoose is an ODM ( Object Document mapper ) for node js & mongo db. It map mongo collections to node js models to provide object oriented way of db operations. It can be installed by using npm in current project directory.

$ npm install mongoose --save

Connection can be made in out app/controller files by

var mongoose = require('mongoose');

Now we need to add model file for our collections.

We will create following models ->


Let see test model code

const mongoose = require('mongoose')
let Schema = mongoose.Schema;

const TestSchema = new Schema(
 string_col: {type: String, default: ''},
 number_col: {type: Number, default: 0},
 bool_col: {type: Boolean, default: null},
 mixed_col: {type: Schema.Types.Mixed, default: ''},
 oid_col: {type: Schema.Types.ObjectId, default: null},
 array_col: [{type: String, default: ''}],
 date_col: { type: Date, default: }

const testModel = mongoose.model('test', TestSchema);
module.exports = testModel;

Here we describe a schema for mongo collection. Key column _id is automatically added and need not to be described. Fields are described by their types. Following types are supported.

a) String
String type defined for string type fields.

b) Number
Number type defined for number (both) type fields.

c) Bool
Bool type can have boolean values true & false.

d) mixed
Mixed type can have any type. It is mainly used when data is uncertain.

e) ObjectId
Mongo key object id field. Mainly used for foreign key implementation from same / other collection key.

f) Date
Date type handle ISO Date formatted data like ISODate(“2018-03-19T12:51:01.585Z”)

g) Array
This type used to insert array type of data. We can define other type as valid values in array like
[{type: String}]
[{type: Number}]
[{type: Mixed}]
[{type: Date}]

We can create multi level array by using following syntax

[[{type: String}]]

If we do not define type and used syntax like [] or [[]]. Field can have any type of data as values of array.

We can used mongoose save API call to save data into collection.

var testModel = require('./models/test');
var testObj = new testModel();
testObj.string_col = 'Kuldeep';
testObj.number_col = 1234;
testObj.mixed_col = {'age': 45};
testObj.array_col = ['John', 'Doe'];
testObj.bool_col = true;
testObj.oid_col = mongoose.Types.ObjectId("5906d4017362098740b23eeb");
testObj.date_col = new Date();, res) => {
if (err) return console.error(err);

This call create new Object for test model with required properties and save call insert data to collection.

If we need to update data we can use either findOneAndUpdate or Save call

USING findOneAndUpdate

  {_id: mongoose.Types.ObjectId("5aafb50bd1443f49a873784c")}, {
  { $set: {
    string_col: "New Str"
 }, {
   upsert: false
 }, (err, res) => {
    if (err) return console.error(err);

First argument is condition on which single record is chosen to save.
Second argument have fields to update.
Third argument is optional. If set upsert true, It insert the data as new record if no matching record with condition was found.

findOne + Save Method

testModel.findOne({_id: mongoose.Types.ObjectId("5aafb50bd1443f49a873784c")}, (err, testObj) => {
  if (err) return console.error(err);
  testObj.string_col = 'NEW DATA';, res) => {
  if (err) return console.error(err);

This method is similar to insert method as we used same save call to update data, Except we do not used new Model, but get object from DB by using findOne call.