scottwrobinson / camo

A class-based ES6 ODM for Mongo-like databases.
556 stars 80 forks source link

Failure Methods (FindOrFail & FindOneOrFail) #75

Open jamespegg opened 8 years ago

jamespegg commented 8 years ago

One of the most useful features in other ORM / ODM's is the "orFail" type methods (e.g. eloquent). At the moment if you use either find or findOne it'll just return null or an empty array if nothing is found. That means you have to do a null or array length check in every case to make sure you've actually got something to work with;

Post.findOne({_id : id}).then(function(post){
    if (post != null) {
        // Do something
    } else {
        // Handle the error
    }
}).catch(function(){
   // Handle the error
});

In the above example you have to handle an "error" in two different places.

This gets a bit clunky if you're using something like Express and have a lot of routes / controllers to deal with. The equivalent failure type method would look like this;

Post.findOneOrFail({_id : id}).then(function(post){
    // Do something
}).catch(function(){
   // Handle the error
});

I've got this working in a fork along with a couple of (really basic) tests. Happy to create a pull request if you're interested?

jampy commented 8 years ago

+1