Mongoose: Encountered an issue while processing post hook error

I have a web application built with Node.js using Express.js, and storing data in a MongoDB database with the help of Mongoose. My challenge is to handle a duplicate key error (error code 11000) from MongoDB while still returning a 204 HTTP response. I plan to achieve this by implementing a post hook on the save method, where I can capture and dismiss the error.

Service Layer

const createMyModel = (req, res, next) => {
  MyModel.create({...data})
  .then(createRes => res.status(204).send())
  .catch(next)
}

Schema - Save Hook

MySchema.post('save', (err, res, next) => {
  if (!err || (err.name === 'MongoError' && err.code === 11000)) {
    // The code to handle the duplicate key error goes here
    next();
  } else {
    next(err);
  }
});

Answer №1

When working with Mongoose, the next callback plays a crucial role in managing a variable known as firstError. This variable stores internal errors such as Duplicate Key Error to prevent users from mistakenly overriding the error state. Even if one attempts to call next() or next(null), it will always check for firstError and trigger a promise rejection.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The image stored in the Images directory of Node.js is not displaying on the website

Having trouble adding an image to my index.ejs file. The code doesn't seem to be pulling the image from the specified /image folder in the second code block. Any tips on how to resolve this issue would be greatly appreciated! const express = require( ...

navigating to a new page using Angular routing following a successful call to an API on an Express server

When using angular routing in a single page application, how can I redirect a page after an API call? Specifically, I want to redirect the user to the profile page after they have called the login API. However, my current method does not seem to be working ...

The file or directory does not exist in ENONET, please check the status of E:clientuildindex.html

Hi there, I'm currently working on a project that involves integrating both Node.js and React.js on the same port. However, I've run into an issue when it comes to setting the path for static files. Despite researching extensively on Stack Overfl ...

The Node.js server refuses to start due to an error that is preventing it

I'm encountering an error while trying to run a node.js server for CRUD operations using Mongoose and Express dependencies. Below is the error message I receive when running the server with the command `node server.js`: ---------- Server.js Code ...

The function Router.use is looking for a middleware function, but instead received an object in node.js /

I encountered an issue while trying to setup routing in my application. Whenever I attempt to initialize a route using app.use() from my routes directory, I receive an error stating that Router.use() requires a middleware function but received an Object in ...

Why does my Node.JS Express request return undefined after submitting a post request from a form?

Having trouble retrieving data from an HTML form using Node.JS/Express. The req.body seems to be empty, returning an undefined value. Node const express = require('express') const bodyParser = require('body-parser') const app = express ...

Guide to obtaining the current upload progress percentage using jQuery and Node.js

I am currently working on uploading a file using jquery, ajax, express, and nodejs. I am looking for a way to display the progress of the upload process. Perhaps there is a plugin or another method that can help with this. I do not need direct answers po ...

What sets express-session apart from cookie-session?

I'm just starting out with Express. Since Express 4.x no longer has bundled middlewares, any middleware I want to use must be required. Reading the README for both express-session and cookie-session on GitHub, I'm finding it difficult to understa ...

Consistently directing to a single page on the Node Js web server

I'm in the process of creating a website with multiple HTML pages. Currently, I have code that successfully links to the login page, but unfortunately, the localstores page also directs to the login page. const express = require('express') ...

When using findOneAndUpdate to modify specific elements within an array, the Mongoose library is failing to update the booleanValue field in the array

Updating a boolean value in an object within an array in a mongo document using mongoose is proving to be tricky. app.post("/api/post/:chorecomplete", function(req, res){ Parent.findOneAndUpdate({parentFirstName: req.body.parentFirstName, parentLastN ...

Why am I not seeing my views when trying to export them from a file in my routes folder?

I've been tinkering around with basic routing in ExpressJS and up to this point, I have implemented two routes: app.get('/', function(req,res) { res.render('index'); }); app.get('/pics', function(req,res) { res.rend ...

Use a for loop to fill an array with values and then showcase its contents

I have been trying to figure out how to populate an array and display it immediately when targeting the route in my NodeJS project. Currently, I am able to console log a list of objects. However, I want to populate an array and show it when accessing loca ...

Can you explain the distinction between res.send and res.write in the Express framework?

As someone who is new to express.js, I am currently exploring the distinctions between res.send and res.write. Can anyone provide some insight into this? ...

"Is it possible to access variables declared in the main app.js file from separate route files in Node.js Express 2.5.5 and if so

Recently, I've started using the latest version of Express (2.5.5) which now automatically creates a ./routes directory in addition to ./views and ./public In the routes directory, there is an index.js file that includes: /* * GET home page. */ e ...

Is it unwise to rely on Sequelize for validating objects that are not stored in a database?

Currently, I am utilizing Sequelize as my ORM and find the powerful built-in model validation to be quite impressive. I am contemplating leveraging Sequelize as a schema validator in specific scenarios where there would not be any actual database writes. E ...

Oops! Looks like there's an issue - XModel isn't linked to YModel in Sequelizejs

After a few weeks of using Sequelize, I encountered an issue that has left me stumped. Despite reading through various similar questions, I have been unable to find a solution. Let me share my models: Merchants.js 'use strict'; var Sequeli ...

Is the populate method of Mongoose causing a disruption in the promise chain?

My mongoose Schema is structured as follows: var Functionary = new Schema({ person: { type: mongoose.Schema.Types.ObjectId, ref: 'Person' }, dateOfAssignment: Date, dateOfDischarge: Date, isActive: Boolean }); var PositionSche ...

Guide on using $lookup with aggregation in Mongoose when dealing with a foreign key within a nested subarray

I am attempting to join three tables in my express-mongo project. One of the tables is named Product and looks like this: Product: _id:5f92a8dfad47ce1b66d4473b name:"Freno 1" createdFrom:5f648f7d642ed7082f5ff91f category:5f92a00c4637a61a397320a1 descripti ...

The expiration time and date for Express Session are being inaccurately configured

I'm experiencing an issue with my express session configuration. I have set the maxAge to be 1 hour from the current time. app.use( session({ secret: 'ASecretValue', saveUninitialized: false, resave: false, cookie: { secure ...

Starting with Node.js and Express, it's essential to properly handle and extract request parameters

I'm currently working on a web application where I need to map identifier-data objects for most server requests. Although I want to override the request handling process without having to manually add mapping to each request. Is there a more efficient ...