我如何解决节点js中的验证错误

时间:2019-12-17 17:22:12

标签: node.js mongodb express validation

我必须进行验证,对于一个idteam,您最多只能创建5名玩家。我将node js与express一起使用,将mlab(mongo db)与heroku一起使用。

    playerModel.count({ idteam: player.idteam }, function (err, count) {
    console.log('el equipo tiene %d jugadores', count);
    if (count > 5){
        throw 'Equipo completo'
    }
  });

我对某个idteam进行计数,当我对保存在count中的数据进行验证时,当满足条件时会出现以下错误

Error [ERR_UNHANDLED_ERROR]: Unhandled error. ('Equipo completo')
at Function.emit (events.js:187:17)
at C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongoose\lib\model.js:4640:13
at C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongoose\lib\utils.js:581:16
at result (C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongodb\lib\operations\execute_operation.js:75:17)
at session.endSession (C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongodb\lib\operations\execute_operation.js:64:11)
at ClientSession.endSession (C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongodb\lib\core\sessions.js:135:41)
at executeCallback (C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongodb\lib\operations\execute_operation.js:59:17)
at callbackWithRetry (C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongodb\lib\operations\execute_operation.js:131:14)
at executeCommand (C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongodb\lib\operations\estimated_document_count.js:47:7)
at server.command (C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongodb\lib\operations\command_v2.js:96:7)
at wireProtocol.command (C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongodb\lib\core\sdam\server.js:253:7)
at C:\Users\Administrator\Desktop\API JUGADORES\node_modules\mongodb\lib\core\connection\pool.js:420:18
at process._tickCallback (internal/process/next_tick.js:61:11)

有人知道为什么会这样吗?

谢谢

1 个答案:

答案 0 :(得分:0)

如果count大于5,则会引发异常。这可能不是必需的,因为您可以简单地返回一个真实的语句,如下所示:

作为等待回调的承诺:

new Promise((resolve, reject) => {
    playerModel.count({ idteam: player.idteam }, function (err, count) {
        return resolve(count > 5);
    });
})
.then(hasMoreThanFive => {
   if (hasMoreThanFive === true) {
       //has more than 5
   }
   else {
       //does not have more than 5
   }
});

或者仅使用回调本身:

playerModel.count({ idteam: player.idteam }, function (err, count) {
    if (count > 5){
        //place code if has more than 5 here
    }
    else {
        //place code if does not have more than 5 here
    }
});

如果您绝对坚持要在5个以上时将此异常抛出,那么您将像这样捕获它:

new Promise((resolve, reject) => {
    playerModel.count({ idteam: player.idteam }, function (err, count) {
        if (count > 5){
            return reject('Equipo completo');
        }
        return resolve(true);
    });
})
.then(() => {
   //does not have more than 5
})
.catch(() => {
    //has more than 5
});