I’ve been learning Mongoose and would like to share few notes. Let’s say we have Invoice schema like below defined in mongoose.
const mongoose = require("mongoose");
const invoiceSchema = mongoose.Schema({
creationDate: {type: Date, default: Date.now},
description: {type: String, required: true},
amount: {type: String, required: true}
});
To this schema I would like to add a new property / key / field that will define the status of the invoice, and this new property takes predefined values, like, an enum.
status: {type: String, enum: ["New", "Assigned", "Completed"]}
Above status is the new property added to my invoice scheme. And mongoose creates a validator that checks if the value is in the given array of strings.
In a real world case we would like to know who created an invoice. For this we need to store the user id (invoice creator id) for each document, given that we have User schema already defined. Below is the property creator that we can define for such cases…
creator: {type: mongoose.Schema.Types.ObjectId, ref: "User", required: true}
Here the property creator is of type ObjectId and it refers to User schema.
Every invoice will have a number, and let’s say we need to maintain an auto-increment number for each document created that will serve as an invoice number. For this we can make use of plugins, we can either create a plugin ourselves or use an existing one. I found one plugin for our use-case called mongoose-auto-increment. Let us use this package as our plugin.
const autoIncrement = require("mongoose-auto-increment");
...
autoIncrement.initialize(mongoose.connection);
invoiceSchema.plugin(autoIncrement.plugin, { model: 'Invoice', field: 'orderNo', startAt: 1 });
Above code will add a new property called orderNo to our schema and will use the plugin mongoose-auto-increment to auto-increment (startAt is set to 1 so we start from 1 … ) the property every time we insert a new document of this type.
This is all we wanted for now!, let us look at the full schema now.
const mongoose = require("mongoose");
const autoIncrement = require("mongoose-auto-increment");
const invoiceSchema = mongoose.Schema({
creationDate: {type: Date, default: Date.now},
description: {type: String, required: true},
amount: {type: String, required: true},
status: {type: String, enum: ["New", "Assigned", "Completed"]},
creator: {type: mongoose.Schema.Types.ObjectId, ref: "User", required: true}
});
autoIncrement.initialize(mongoose.connection);
invoiceSchema.plugin(autoIncrement.plugin, { model: 'Invoice', field: 'orderNo', startAt: 1 });
module.exports = mongoose.model("Invoice", workOrderSchema);
Note: To use the plugin mongoose-auto-increment you first need to install it $npm install mongoose-auto-increment.