scottwrobinson / camo

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

Examples catching validation errors? #28

Closed kokujin closed 8 years ago

kokujin commented 8 years ago

Are there production usable examples that one can reference? For example, catching validation errors, missing embedded documents e.t.c? Thanks

kokujin commented 8 years ago

At the moment, trying to save documents with a field marked as unique using neDB just stops Camo, and as a result, my application from working

scottwrobinson commented 8 years ago

The best way to handle errors in Camo (and any other promise-based JS library) is to use the .catch() method. Here is an example, using similar code to your other question about .count():

'use strict';

var connect = require('camo').connect;
var Document = require('camo').Document;

class Company extends Document {
    constructor() {
        super();
        this.name = {
            type: String,
            unique: true
        };
    }
}

connect('nedb://memory').then(function(db) {
    var ibm = Company.create({
        name: 'ibm',
    });

    var ibm2 = Company.create({
        name: 'ibm',
    });

    Promise.all([ibm.save(), ibm2.save()]).then(function() {
        console.log('Saved ibm2!');
    }).catch(function(err) {
        console.log('Couldn\'t save ibm2, so we should handle the error here!');
    });

});

If you run this you should see "Couldn't save ibm2, so we should handle the error here!" printed to the console. The .catch() method is called whenever an error is thrown within a Promise. That's where you should handle the error.

Hope this helps!

kokujin commented 8 years ago

It helps! Thanks!