Best practice for checking Mongoose schema and displaying custom error message

I started learning Node.js, and one thing that confuses me a bit is checking the circuit.

What would be the best practice for checking data and displaying custom error messages to the user?

Say we have this simple diagram:

var mongoose = require("mongoose"); // create instance of Schema var Schema = mongoose.Schema; // create schema var Schema = { "email" : { type: String, unique: true }, "password" : String, "created_at" : Date, "updated_at" : Date }; // Create model if it doesn't exist. module.exports = mongoose.model('User', Schema); 

I would like to have registered users with unique emails, so I added unique: true to my schema. Now, if I want to show an error message to a user who says why it is not registered, I would get a response something like this:

  "code": 11000, "index": 0, "errmsg": "E11000 duplicate key error index: my_db.users.$email_1 dup key: { : \" test@test.com \" }", "op": { "password": "xxx", "email": " test@test.com ", "_id": "56895e48c978d4a10f35666a", "__v": 0 } 

This is all a little dirty, and I would like to display for sending to the client side only something like this:

 "status": { "text": "Email test@test.com is already taken.", "code": 400 } 

How to do it?

+5
source share
1 answer

The easiest way to deal with error messages for a unique restriction in the mongoose is to use a plugin like mongoose-beautiful-unique-validation . This makes error messages look like regular validation error messages.

0
source

Source: https://habr.com/ru/post/1239738/


All Articles