1

I've been looking for an answer on Google, and based on the results found, I am able to check whether a table exists or not in CouchDB, using nano module.

However, when I try to make it a custom function, it always return "undefined" no matter what. Here is the function:

var exists = function( id ) {

    this.head( id, function( err, body, header ) {

        if ( header[ 'status-code' ] == 200 )
            return true;
        else if ( err[ 'status-code' ] == 404 )
            return false;

        return false;

    });

}

Call it:

nano.db.create( 'databaseName', function() {

    var users = nano.use( 'databaseName' );

    console.log( exists.call( users, 'documentToCheck' ) );

});

What exactly was wrong here? I can't seem to figure it out correctly.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
cuzmAZN
  • 377
  • 1
  • 7
  • 25

1 Answers1

2

Your function exists returns undefined, because inner anonymous function returns your needed value.

Cure for this disease is to refector your function exists

var exists = function( id , cb) {

    this.head( id, function( err, body, header ) {

        if ( header[ 'status-code' ] == 200 )
            cb(true);
        else if ( err[ 'status-code' ] == 404 )
            cb(false);

        cb(false);

    });

}

Usage:

exists.call(users, 'documentToCheck', function(check) {
    console.log(check);
});
  • 1
    I knew it has to do with callbacks :-/. Thanks a lot for pointing it out! – cuzmAZN Aug 20 '14 at 22:37
  • hi. So i've tried implementing a similar function but it returns to me an error saying "header" does not contain a property 'status-code' – Kevin Tommy Aug 01 '23 at 14:18