Home > Back-end >  Retrieving particular value from mongo documents using mongoose and nodejs
Retrieving particular value from mongo documents using mongoose and nodejs

Time:10-13

I am looking forward to check into the docs of the collection model and return a particular value, based on its key , from each one of them however i am missing something regarding the scope of how the model.find() actually works.

My documents within the model collection follow the following structure:

{_id: xxx,
 date: 2021-08-08T00:00:00.000 00:00
 data [array of data]}

And my code is as it follows

async (model, key) => {
  const getFilteredDataByKey = await model.find({}, (err, data)=> {
  data.map((doc) => doc[key]);
  });
  console.log('getFilteredDataByKey', getFilteredDataByKey)
  return getFilteredDataByKey;
};

The problem I am getting is that getFilteredDataByKey returns all the docs, when i guess it should return the filter uniquelly doesnt it?

My ideal output would be to return uniquely the array of the values, based on the keys, from getFilteredDataByKey

CodePudding user response:

Your console.log is returning an empty list since model.find is asynchronous, meaning the callback function has not been invoked yet. I suggest you to use the following code and "await" the result instead of using a callback function:

const listado = (await model.find({}, 'date')).map(item => item.date);
console.log('listita',listado)

Explanation: You first await the find function (you have to define your function as async) and only retrieve property 'date'. After that you map your document array to an array of plain dates.

  • Related