node.js - Mongoose sends existing document when validation failed -


i have post request create document. problem mongoose sets original document part of response when validation fails. make mongoose not send existing document, hashed password.

this response

{ "code": 11000, "index": 0, "errmsg": "e11000 duplicate key error collection: ole.tournament index: name_1 dup key: { : \"first tournament\" }", "op": {     "name": "first tournament",     "tourntype": "single elimination",     "seriestype": "bo1",     "password": "$2a$10$xha5ukpk.xh4qrodhf/os.djs9ccu3c8ppcm8j99rocyphs3x0tic",     "_creator": "5992734ebaa773270898e248",     "_id": "59927361baa773270898e24a",     "participants": [],     "starteddate": null,     "createddate": "2017-08-15t04:06:57.640z",     "__v": 0 } } 

this code i've added mongoose doesn't send password, works when creating or updating document, not when path validation fails:

tournamentschema.methods.tojson = function(){   var tournament = this;   var tournamentobject = tournament.toobject();   return _.omit(tournamentobject, "password"); } 

this route

.post('/add', authenticate, (req, res) => {   req.body._creator = req.user._id;   tournament = new tournament(req.body);   tournament.save().then((tourndoc) =>{     res.status(200).send(tourndoc);   }).catch((e) => {     res.status(400).send(e);   }) }) 

i know quick way fix omitting in catch block, there mongoose way this?

thanks.

you need send errmsg ie error message client. not practice send full error object client. can @ below code:

.post('/add', authenticate, (req, res) => {    req.body._creator = req.user._id;    tournament = new tournament(req.body);    tournament.save().then((tourndoc) =>{       res.status(200).send(tourndoc);    }).catch((e) => {       res.status(400).send(e.errmsg);    }) })  

or can send custom error message client below:

.post('/add', authenticate, (req, res) => {    req.body._creator = req.user._id;    tournament = new tournament(req.body);    tournament.save().then((tourndoc) =>{       res.status(200).send(tourndoc);    }).catch((e) => {       if(e.code == 11000) {          res.status(409).send("validation failed!!");       }       res.status(500).send("error occurred!! please try again.");    }) })  

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -