I am trying to save Sensor values to my mongodb database. I am using promise to do proper error handling. I am using then() and catch() but I guess I am not doing it right. I send a group Id so it checks if the group id exists then only it stores sensor information.
Here is my code.
router.post('/data/:group_id', function(req,res,next){
var group_id = req.params.group_id;
User.find({group_id : group_id}).then(function(user){
var object_id = user[0]._id;
var datas = req.body;
var data = new Data({
user : object_id,
value: datas.value,
valueString : datas.valueString,
sensorStatus : datas.sensorStatus,
timeStamp : new Date().toJSON()
});
data.save().then(function(data){
res.send('Data Saved');
});
}).catch(function(e){
if(e.code === undefined){
res.send('Group id does not exist');
}else{
res.send(e);
}
});
});
if I send a group Id that does not exist it does say Group id does not exist, but if I send a wrong json data for saving my sensor information, there is no error but my postman-app which I am using to send information gets stuck. Here is a error I purposely generated with a valid group ID.
I am new to this so need to understand how promise handles the error for first if the group_id cannot be found and second if the sensor json information is wrong.
Sent to http://localhost:3000/api/data/3
{
"value1" : "79" ,
"valueString" : "Small data",
"sensorStatus" : "false"
}
Extra information User and Datas model. Note( Dint add the require and export part)
var schema = new Schema({
group_id : {type : Number, required: true},
password : {type : String, default: null},
project : {type : String , default : null}
});
var schema = new Schema({
user: {type: Schema.Types.ObjectId, ref: 'User'},
value :{type : Number , required : true} ,
valueString : {type : String, required : true},
sensorStatus : {type : Boolean , default : 0},
timeStamp : {type :String , required : true}
});
Right, you're falling to a common pitfall: Don't nest .then() clauses, instead, return Promises and chain:
Don't do
foo().then(() => {
bar().then(() => {
baz();
}
}
Return the Promise from inside of the .then() and chain, like so:
foo()
.then(() => { return bar(); })
.then(() => { return baz(); });
Or the shorter version
foo()
.then(() => bar())
.then(() => baz());
In your case:
router.post('/data/:group_id', function(req,res,next){
var group_id = req.params.group_id;
User.find({group_id : group_id})
.then(function(user){
// bla bla bla
return data.save();
})
.then(function(data){
return res.send('Data Saved');
});
.catch(function(e){
if(e.code === undefined){
res.send('Group id does not exist');
}else{
res.send(e);
}
});
});
As a common rule: Always return or throw from a .then() handler.