Using MongoDB with Mongoose — Pre Middleware Errors and Post Middlewares
3 min readJan 19, 2021
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.
Errors in Pre Hooks
We can raise errors in pre hooks in various ways.
For example, we can write:
async function run() {
const { createConnection, Schema } = require('mongoose');
const connection = createConnection('mongodb://localhost:27017/test');
const schema = new Schema({
name: { type: String, required: true },
age: Number
});
schema.pre('save', (next) => {
const err = new Error('error');
next(err);
});
const Kitten = connection.model('Kitten', kittenSchema);
}
run();
to pass an Error
instance in the next
method.
Also, we can return a promise:
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
});
schema.pre('save', (next) => {
const err = new Error('error');
return…