我总是使用 if (!result)
来捕获结果为 null 的情况,但由于某种原因,这在这里不起作用?!?
exports.getDiscount = function(req, callback) {
var discountModel = require('../models/discountModel');
var discountTable = mongoose.model('discountModel');
discountTable.findOne (
{ _id: req.body.discount }
,function (err, data) {
if (err) {callback( { error:true, err:new Error('findDiscount: ' + err) } )};
console.log("data " + data)
console.log("json: " + JSON.stringify(data, null, 4));
if (!data) {
callback( { error:true, err:"NOT FOUND: " + req.body.discount + " was not found" } )
}
console.log("WHY ARE YOU NOT STOPPING?!?!")
console.log("data " + data)
console.log("json: " + JSON.stringify(data, null, 4));
if (Math.round(new Date().getTime()/1000) > data.expires) {
callback( { error:true, err:"EXPIRED: " + new Date(data.expires*1000).toDateString() + " " } )
}
callback( { error:false, percent:data.percent } );
});
}
这是我的控制台输出
为什么if (!data) {
处的回调没有捕获这个空值?
最佳答案
在执行 if (!data) { ... }
后,代码中没有任何内容会停止执行。 (或者,就此而言,if (err) { ... }
等)
很可能您只是想在调用 callback()
函数后返回 false;
或其他内容
如果您在该 if
block 内抛出一个 console.log()
,它应该显示代码正在进入该 block 。
关于javascript - mongodb 的结果为 null,但 if (!result) 未捕获它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685794/