【问题标题】:Handle CastError with Mongoose using Promises使用 Promises 处理 Mongoose 的 CastError
【发布时间】:2014-05-27 03:24:09
【问题描述】:

我正在使用 Mongoose (v. 3.8.8) 来更新我的模型“权限”的一些数据。这是架构:

var PermissionSchema = new Schema({

        name : { 
            type: String, required: true, index: true
        },
        httpVerb : { 
            type: String, required: true
        },
        url : { 
            type: String, required: true
        }
});

mongoose.model('Permission', PermissionSchema);

现在我在另一个模块中有一个使用 Promise 的函数:

module.exports.updatePermission = function (id, updatedPermission) {

    var conditions = {_id: id};

    var promiseUpdate = Permission.update(conditions, updatedPermission).exec();

    logger.debug('this line is not executed when CastError occurs');

    var promiseFind = promiseUpdate.then(function (permission) {
        return Permission.findOne(conditions).exec();
    }).then(null, function (error) {
            logger.info('CastError does not get in here');
            logger.error(error);
            //error handled here
        });

    return promiseFind;
}

当我使用此示例参数调用该函数时:

id: 53496a2e1722ff2d1a55a4d2
updatedPermission: {name: 'this is my new name'}

一切正常,因为集合中已经存在 _id 确实

现在,当我使用以下参数时,故意传递一个无效且不存在的 _id :

id: 53496a2e1722ff2d1a55a4d22
updatedPermission: {name: 'this is my new name'}

我得到以下异常:

CastError: Cast to ObjectId failed for value "53496a2e1722ff2d1a55a4d22" at path "_id"
    at ObjectId.cast (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/schema/objectid.js:116:13)
    at ObjectId.castForQuery (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/schema/objectid.js:165:17)
    at Query.cast (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/query.js:2291:32)
    at castQuery (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/query.js:2015:18)
    at Query.update (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/query.js:1704:21)
    at Function.update (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/model.js:1606:13)
    at Object.module.exports.updatePermission (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/app/repository/auth/PermissionRepository.js:50:36)

我原以为当 promise 被拒绝时会出现此错误,即在 updatePermission 函数的第二个“then”中。

问题是:这是 Mongoose 的错误吗? - 如果不使用 try/catch,我该如何处理?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    刚刚发现如何在这种特殊情况下使用 Promise。 Mongoose 有一个按预期工作的函数 findOneAndUpdate (http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate)。 CastError 通过拒绝传递。这样我就可以在没有 try/catch 块的情况下处理错误。

    这是代码(PermissionRepository.js):

    module.exports.updatePermission = function (id, updatedPermission) {
        var conditions = {_id: id};
    
        var promiseUpdate = Permission.findOneAndUpdate(conditions, updatedPermission).exec();
    
        return promiseUpdate;
    }
    

    下面的代码调用了前一个(CastError在第二个“then”中处理):

    module.exports.updatePermission = function (req, res) {
        var id = req.query.id;
        var updatedPermission = req.body;
    
        var permissionRepository = repositoryFactory.getPermissionRepository();
        var promise = permissionRepository.updatePermission(id, updatedPermission);
    
        promise.then(function (permission) {
            if (!permission) {
                res.status(404).json(Error.resourceNotFound);
            } else {
                res.status(200).json(permission);
            }
        }).then(null, function (error) {
                logger.error(error.stack);
                res.status(500).json(Error.databaseError(error.message, error));
            });
    }
    

    现在我很确定方法更新中存在错误 (http://mongoosejs.com/docs/api.html#model_Model.update)。我会举报的。

    【讨论】:

      猜你喜欢
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      相关资源
      最近更新 更多