0
I am trying to update an array with values returned by Mongoose. But the array returns empty. It follows the code snippet:
let y = [];
Vendas.countDocuments(
{ dt_encerramento: { $gte: jan, $lte: abr }},
function(err, os) {
y.push(os);
}
);
Give up console.log(y)
inside the callback, I have the values. I run right after the countDocuments
, returns an empty array.
Would anyone know what I’m doing wrong?
I appreciate the answer João, but I still haven’t been able to take the value of the variable and move to the array. I tried several ways, follow one of them:
async function docs() {
 const numDocs = await Vendas.countDocuments({ dt_encerramento: { $gte: jan, $lte: abr }}).exec();
 return numDocs;
 }
 docs().then(function (err,n) {
 y.push(n);
 });

– Fábio Medeiros
You need to understand the difference between asynchronous work and synchronous work. In this case for example, within another async function, you can do:
y.push(await countDocuments())
– João Pedro Henrique