Good morning,
I thought that following the instructions of Push element into nested array mongoose nodejs I would manage to solve my issue but I am still stuck.
I am trying to get the results of a Mongoose query into an array. The below code works when the number of objects is relatively small, but I get a "parse error" whenever the volumen increases.
I can see I am not considering the fact that the code is asynchronous but my the attemps I have tried end up in Promise { <pending> }
at best.
const Collection = require("./schema");
const connection = require("mongoose");
let data = [];
Collection.find({},(e,result)=>{
result.forEach(doc =>{
data.push([doc["a"],
doc["b"]])
});
})
.then(()=>connection.close())
module.exports = data;
The above is obviously wrong, since I am not respecting the async nature of the operation.
I implemented the below function, but I don't understand how I should resolve the promise.
async function getdata() {
const cursor = Collection.find().cursor();
let data = []
await cursor.eachAsync(async function(doc) {
await new Promise(resolve =>resolve((data.push(doc))));
});
}
The aim is that when I do let data = require("./queryResult.js")
data
contains all the necessary data [[a,b],[a,b]]
Could anybody give me a hand on this one?
Many thanks in advance.