javascriptnode.jsarangodbarangojs

Database reference is not defined in arangojs on node js


I am trying to use ArangoJS drive on Node JS, when I add following code to main app.js file it works but when added to a function in a class in different file it throws an error.

Database is not defined

Code is as follows

class User {
insertUser() {
        Database = require('arangojs').Database;
        db = new Database();
        db.useBasicAuth("", "");
        db.useDatabase('_system');

        collection = db.collection('Users');
        doc = {
          _key: 'firstDocument',
          a: 'foo',
          b: 'bar',
          c: Date()
        };
        collection.save(doc).then(
          meta => console.log('Document saved:', meta._rev),
          err => console.error('Failed to save document:', err)
        );
}
contructor() {

}
}



 module.exports = User;

If I use the code from insertUser function in app.js directly it works fine.

Kindly advice

Thanks

Note: I am using Express with Node js


Solution

  • You need to require database outside of the class and use const:

    const { Database } = require('arangojs');
    class User {
    contructor() {}
    
    insertUser() {
            db = new Database();
            db.useBasicAuth("", "");
            db.useDatabase('_system');
    
            collection = db.collection('Users');
            doc = {
              _key: 'firstDocument',
              a: 'foo',
              b: 'bar',
              c: Date()
            };
            collection.save(doc).then(
              meta => console.log('Document saved:', meta._rev),
              err => console.error('Failed to save document:', err)
            );
    }
    
    }
    
    
    
     module.exports = User;