Member-only story

Using MongoDB with Mongoose — Middlewares

John Au-Yeung
3 min readJan 19, 2021

--

Photo by Jacek Dylag on Unsplash

To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.

In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.

Update Validators Only Run On Updated Paths

We can add validators to run only on updated paths.

For instance, we can write:

async function run() {
const { createConnection, Schema } = require('mongoose');
const connection = createConnection('mongodb://localhost:27017/test');
const kittenSchema = new Schema({
name: { type: String, required: true },
age: Number
});
const Kitten = connection.model('Kitten', kittenSchema);
const update = { color: 'blue' };
const opts = { runValidators: true };
Kitten.updateOne({}, update, opts, (err) => {
console.log(err)
});
const unset = { $unset: { name: 1 } };
Kitten.updateOne({}, unset, opts, (err) => {
console.log(err);
});
}
run();

then only the second updateOne callback will have its err parameter defined because we unset the name field when it’s required.

Update validators only run on some operations, they include:

--

--

No responses yet