Mongoose static method returns bluebird promise

I am creating a static mongoose "load" method so that my main controller function can use it (for chaining and error handling).

UserSchema.load('54ae92dd8b8eef540eb3a66d')
.then(....)
.catch(....);

      

The thing is, id is something wrong, so I need to catch this error. and i think it's better to do it at the model level.

When I do the following, the controller can catch this error.

UserSchema.statics.load = function(id) {

    if (!mongoose.Types.ObjectId.isValid(id)) {
        return Promise.resolve().then(function() {
            throw new Error('not a mongoose id');
        }); ------------( * )
    }

    return Promise.cast(this.findOne({
        _id: id
    }).exec());
};

      

But if I only do the following, then the error will not be successfully thrown in the controller function .catch.

AchievementSchema.statics.load = function(id) {
    if (!mongoose.Types.ObjectId.isValid(id)) {
        throw new Error('not a mongoose id');
    }
    return Promise.cast(this.findOne({
        _id: id
    }).exec());
};

      

so my question is, am I doing it right? If so, is it easier to write a statement (*)? What I am doing seems to be ugly .. Thanks.

+3


source to share


1 answer


Yes, there is an abbreviated name Promise.reject

.

Your code in:

if (!mongoose.Types.ObjectId.isValid(id)) {
    return Promise.resolve().then(function() {
        throw new Error('not a mongoose id');
    }); ------------( * )
}

      

It can be written as:

return Promise.reject(new Error("Not a mongoose id");

      



You can do even better, though Promise.method

, to ensure that anything that can return a promise will return a promise:

UserSchema.statics.load = Promise.method(function(id) {

    if (!mongoose.Types.ObjectId.isValid(id)) {
        throw new Error('not a mongoose id: ' + id);
    }
    return this.findOne({ _id: id }).exec());
});

      

This will cause the result to findOne

lead to the reliable Bluebird promise and convert throw

to rejection for you. You might want to consider adding a subclass Promise.OperationalError

rather than Error

.

As the unrelated review Promise.cast

was deprecated in favor of Promise.resolve

over a year ago.

+9


source







All Articles