Search code examples
javascriptnode.jsmodel-view-controllerrequiremodularity

How can I access objects inside objects directly in Node.js?


Let's say that I have two files named dbPerson.js and dbCar.js both with their own methods like:

dbPerson.js:

module.exports = {
    getAll(callback){}
}

dbCar.js:

module.exports = {
    getOne(callback){}
}

And then I have another file named db.js that would import those files:

const dbPerson=require('./dbPerson');
const dbCar=require('./dbCar');

And ultimately I have a main file which imports db.js:

const db=require('./db');

I want to be able to call the methods by using db.getAll() and db.getOne(), but this way I would need to use db.dbPerson.getAll() and db.dbCar.getOne(), is there a way so I don't need to do that?

UPDATE: I found that the answer below helps me but thanks for everyone who tried to understand what I meant, next time I'm gonna try to be more clear!


Solution

  • There are few ways to do it. Which path you take should depend on your requirements.

    First let's assume you want to merge these two objects(dbCar and dbPerson). Then you can do it simply using the object spread syntax.

    // db.js
    module.exports = {
      ...dbPerson,
      ...dbCar,
    }
    

    Note that doing this way, conflicting properties of dbPerson will be overridden by the properties of dbCar. And by the naming, it does not make sense to merge these two objects (What would you call something that is a Person and also a Car?).

    Another approach is to use a proxy object to forward the calls.

    // db.js
    module.exports = {
      getAll: dbPerson.getAll,
      getOne: dbCar.getOne,
    }