1

I am trying to implement a function in Express to return a list with data from a mongoose model. 'MiModelo' is the mongoose model created from a Schema.

//Get data in the DB
function getAllData()
{
    var promesa = MiModelo.find().exec();
    console.log(promesa);
    console.log("---");
    var miLista=[];
    async = require('async');
    async.parallel([function(){
        promesa.then(function(datos)
        {
            datos.forEach(function(dato){
                console.log("dato: " + dato.numero)
                miLista.push(dato.numero);
            });
        });
    }],function(){
        console.log(miLista);
    });
    return miLista;
}

In the final console.log() I am able to get all 'numero' field values from the database but the return is empty when I call this function elsewhere. I know it is because it is asynchronous.

I have read the answer in this question: How to make a function wait until a callback has been called using node.js but I do not know how to adapt my function.

Any help is appreciated.

Thank you for your time and help.

John Doe
  • 65
  • 1
  • 6
  • `MiModelo.find().then(datos => { let list = datos.map(({ numero }) => numero ); console.log(list)); })` Resolve Promise which returns an array `.map()` the values from the array. This syntax should be supported from Node 6.x which is the oldest version you should be using. – Neil Lunn Jun 10 '18 at 11:43

1 Answers1

0

The whole function can be simplified to a few lines:

async function getAllData() {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
    const datos = await MiModelo.find().exec();

    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
    const miLista = datos.map(dato => dato.numero)

    return miLista;
}

which you can then call like so:

const data = await getAllData()

// or

getAllData().then(data => console.log(data))
Cisco
  • 20,972
  • 5
  • 38
  • 60