mongodb错误处理使用exec

时间:2017-04-17 21:45:32

标签: node.js express mongoose error-handling

我有ExpressJS,NodeJs,Mongoose应用程序。 我写了如下的mongodb代码,它工作正常。

module.exports.getStudentid = function(id, callback) {

    Student
        .find({ _id: id })
        .populate('marks')       
        .exec(callback);
}

但是它在NodeJS中的错误处理方面是一个很好的代码吗?它会将错误传递给下一层吗?如何改进上述代码以使用正确的错误处理?

1 个答案:

答案 0 :(得分:0)

有一件事应该是定义你的回调函数来支持你的错误。您的回调应如下所示:

function (err, student) {
  if (err) {
     // handle error err, will have your error
     return;
  } 
  return student;
}

如何将它传递到下一层将取决于你在注释行上做什么...我的建议,改变这个使用promises:

const Q                 = require('q');
module.exports.getStudentById = function getById(id) {
    let deferred = Q.defer();
    Student
        .find({ _id: id })
        .populate('marks')       
        .exec(function doAfterExec(err, student){ 
          if (err) {
            deferred.reject(err);
          }
          deferred.resolve(student);
    });
 return deferred.promise;
}

然后调用它,假设您以前的模块被称为StudentIO

const io = require("StudentIO");
io.getStudentById(id)
.then(function doSuccess(result) {
   console.log("yeeei!!!", result);
})
.fail(function doError(err) {
   console.log("buuu", err);
});

如果您使用新的=>语法,这可能会更清晰,但我没有包含它,因为不确定您是否使用它。所以我使用了常规函数符号。

希望这可能会有所启发。看看Q和promises ......它可以很容易地摆脱回调地狱的情景。