0

I currently have the following schema:

Schema({ _id: { type: Number, default: Math.floor(Date.now() / 1000) + 24 * 60 * 60 }, userID: { type: Number, require }, assignmentID: { type: Number, validate: { validator: function (v) { if (!v) { Promise.reject(false); } else { Assignment.findById(v, (assignmentErr, assignmentDoc) => { if(assignmentErr || !assignmentDoc){ Promise.reject(false); } else{ Promise.resolve(true); } }) } }, message: 'Invalid assignment ID.' } } 

The issue I am facing is that I keep getting warnings in the console that I am not handling the rejected promises. Also the document is saved in the database even though the promise is rejected.

The way I save the new document is the following:

schema.save((err, savedDoc) => { } 

How can I solve this issue or is there a better way to do complex validation like this?

1 Answer 1

1

You can try following code:

 assignmentID: { type: Number, validate: { validator: function (v) { if (!v) { return Promise.reject(false); } return Assignment.findById(v) .then(assignmentDoc => { if( !assignmentDoc){ return Promise.reject(false); } else{ return Promise.resolve(true); } }) .catch(error => { return Promise.reject(error ); }) }, message: 'Invalid assignment ID.' } } 

Update You can also try as like as given below:

 assignmentID: { type: Number, validate: { validator: function (v) { if (!v) { return Promise.reject(false); } return new Promise( (resolve, reject) => { Assignment.findById(v, (assignmentErr, assignmentDoc) => { if(assignmentErr || !assignmentDoc){ reject(false); } else{ resolve(true); } }) }); }, message: 'Invalid assignment ID.' } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much - it works! Could you please explain the difference between yours and mine as I am not sure I understand it fully?
As far what I can understand is that, you are resolve/reject, but never return it. I'm updating my answer which might be more understandable to you, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.