Let's say you have this schema setup in mongoose:
var personSchema = new Schema({
name: String,
address:{
city: String,
postalCode: Number
}
});
You have this post:
// /api/person
exports.newPerson = function(req, res){
var person = JSON.parse(person);
//Validation code here
mognoose.model('person').create(person
res.send(200)
}
What's the best way to check that all keys are provided in the post? If anything is missing, I would like to have a 400 error with a message like: 'insufficient data provided, check docs..' or something like that.
You could do:
if(!person.name || !person.address ..){
res.send(404, {message: 'Not sufficient data'})
return;
}
But is this the best way to do it? What if you have a schema with 30 keys? Is there any nicer way of doing this?
You can try this :
var personModel = new mongoose.model('person');
personModel.set(person); // just set temp person object
personModel.save(function (err, saved) {
if (err) {
// your 400 error
return;
}
// saved = person with mongoDb fields seted (_id, __v, ...)
});