Jamie Jordan Jamie Jordan - 6 months ago 30
Node.js Question

node.js callback strange behavior

I face strange callback issue. I expect result return something but it didn't. Someone spot my mistake?

Models

module.exports.updateStatus = function(updateObj, callback){
var order_id = updateObj.order_id,
order_status = updateObj.order_status;
Order.findOneAndUpdate({"_id": order_id}, {$set: {order_status: order_status}},{new: true});


My Routes

var Orders = require('../models/orders');
router.post('/update_status',function(req,res,next){
var updateObj = {
'order_status':req.body.order_status,
'order_id':req.body.order_id
}
Orders.updateStatus(updateObj,function(err,result){
console.log(result) // nothing been return here
})

})


I check my db, the update is actually working fine. I do

module.exports.updateStatus = function(updateObj, callback){
var order_id = updateObj.order_id,
order_status = updateObj.order_status;
Order.findOneAndUpdate({"_id": order_id}, {$set: {order_status: order_status}},{new: true},function(err,result){
console.log(result)// it work here
});

Answer

You’re never calling callback in updateStatus, I don’t see why it would ever be called.

If you want it to be called, call it.

The findOneAndUpdate statement of updateStatus should be:

Order.findOneAndUpdate(
    {"_id": order_id},
    {$set: {order_status: order_status}},
    {new: true},
    callback
);