scottwrobinson / camo

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

Problems with "count()" #27

Closed kokujin closed 8 years ago

kokujin commented 8 years ago

I tried to test the count() function, given this example:

connect(uri).then(function(db) {
    database = db;
    console.log('db: ', db);

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

    // ibm.save().then(function(l) {
    //     console.log('ibm: ', l.id);
    // });

    Company.loadMany({
        name: 'ibm'
    }).then(function(doc) {
        //console.log('docs:', doc);
    }).count(function(count) {
        console.log('count----> ', count);
    })

    Company.count({
        name: 'ibm'
    }).then(function(count) {
        console.log('count:', count);
    })
});

In both log cases, nothing happens, no errors or output. Am i doing something wrong? Thanks

scottwrobinson commented 8 years ago

Hi, there are a few problems with your code. The part that starts with Company.loadMany... doesn't work because you're calling .count() on a Promise object, not the Document object.

The second part of your code (that starts with Company.count...) doesn't work because you haven't yet saved the IBM instance. The method .create() only creates an instance of the Document, but doesn't save it. You must call .save() first. Please see my code below for a working example:

'use strict';

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

class Company extends Document {
    constructor() {
        super();
        this.name = String;
    }
}

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

    // Does not work! Can't call '.count()' on a Promise
    /*Company.loadMany({
        name: 'ibm'
    }).then(function(doc) {
        //console.log('docs:', doc);
    }).count(function(count) {
        console.log('count----> ', count);
    });*/

    ibm.save().then(function() {
        return Company.count({name: 'ibm'});
    }).then(function(count) {
        console.log('count:', count);    // Prints "count: 1"
    });

}).catch(function(err) {
    console.log('err:', err);
});

Hope this helps! Let me know if you have any other questions.