I want to create a restful API with Node.js, Express, MongoDB and Mongoose.
Schema, model and route are below:
// Schema
var OperatorSchema = new Schema({
name : { type: String, unique: true , required: true},
short_name : { type: String, unique:true, required: true },
});
Operator = mongoose.model('Operator', OperatorSchema);
// My Api for Operator
app.post('/api/operators', common.createOperator);
exports.createOperator = function(req, res){
Operator.create(req.body, function (err, operator) {
// If failed, return error message
if (err) {
console.log(err);
res.send(404, err)
}
else {
res.send(operator)
}
})
};
I have three questions:
1 - Handling error like that I found that the err object passed to the callback has a different structure depending if the error comes from mongoose or mongo.
// Mongo Error:
{
"name": "MongoError",
"err": "E11000 duplicate key error index: ussdauto.operators.$name_1 dup key: { : \"OpTest\" }",
"code": 11000,
"n": 0,
"connectionId": 231,
"ok": 1
}
// Mongoose Error:
{
"message": "Validation failed",
"name": "ValidationError",
"errors": {
"short_name": {
"message": "Path `short_name` is required.",
"name": "ValidatorError",
"path": "short_name",
"type": "required"
}
}
}
I don't want to expose all the details about errors: only a message explaining the error is enough, no need for to know if it's a mongoerror or a validationError for example. How do you manage it?
2 - The second question is more global: I'll have multiple API and each time I'll need to do the same work: check if there is errors, if some return via API in JSON the error message and if not continue normally. How can I use only one function to process errors and use it everywhere?
3 - I came from a python world (Django in fact) where Tastypie was a really great module which was handling all of that stuff itself. Do you know if such a module exists for Node.js + Express?