1


I'm usually working with java.
I'm so confused that I used to code with node.js.

Environment : express + mongoose

When I try to use my data from database, I usually make my code with dao-pattern.

If I suppose to call two of variables from each table in database,

ex)
String title = user_dao.getData("title");
String code = book_dao.getData("code");

However I knew that nodes couldn't use it this way. When I call up two variables as above :

database.UserDaoModel.get(options, function(err, results) {
    var title = results._doc.title;

    database.BookDaoModel.get(options, function(err, book_results) {
        var code = book_results._doc.code;

As you see I have to define new line for BookDaoModel... in order to get code value.I think this is really inefficient. The example above simply brings in two data but you know we need to add more function over 5 or 6 method?

  • user verfication
  • device verification
  • etc...

Is there any way that I can use the dao-pattern I used in Java in a node?

I don't want to use every callback to get the data step by step. If I try to get each of the three data from three tables, I must use three callbacks.

I want to finish it all in one line.

Richard
  • 351
  • 4
  • 17
  • Simpler means make use of any ODM, like Mangoose. It would be so much easier for you, just look at it: https://mongoosejs.com/docs/index.html – Izio Feb 08 '19 at 08:11

1 Answers1

1

You need to wrap your functions with promises, for example,:

function get(db,model,options){
    return new Promise((res,rej) => {
        db[model].get(options,(err,val) => {
            if (err) rej(err);
            res(val);
        }
    });
}

and then:

async function run(){
    const results = await Promise.all([
        get(database,"UserDaoModel",options),
        get(database,"BookDaoModel",options)
    ]);
    const title = results[0]._doc.title,
        code = results[1]._doc.code;
}

You can add any number of gets in Promise.all(), and acces them in the results array. (I forgot to say, but of course, you need to call the run() function)

Matei Adriel
  • 94
  • 1
  • 5