Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用exec处理whlle的mongodb错误_Node.js_Express_Mongoose_Error Handling - Fatal编程技术网

Node.js 使用exec处理whlle的mongodb错误

Node.js 使用exec处理whlle的mongodb错误,node.js,express,mongoose,error-handling,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中的错误处理方面是否是一个好代码。它会将错误

我有ExpressJS、NodeJs、Mongoose应用程序。 我已经编写了下面这样的mongodb代码,它工作得很好

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

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

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

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

function (err, student) {
  if (err) {
     // handle error err, will have your error
     return;
  } 
  return student;
}
如何将其传递到下一层将取决于您在注释行上所做的操作。。。我的建议是,将此更改为使用承诺:

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和承诺。。。它可以很容易地摆脱回调地狱场景。

CB详细信息在这个pgI的示例代码中,我正在使用mongoose,我更关心在使用我使用的构造时的错误处理