Moongose can't return modified Array

Written by Arvind

I’m trying to modify the return data from the mongoose promo.find(), but it won’t let me change it. In the code below, you will see that I’m trying to assign the “day” as the key.

const queryPromo = Object.assign({ 'foreign_key' : req.params.id });
const dataPromo = await Promo.find(queryPromo, function(err, data) {
  if (err) return [];
  return data;

  let promos = {};
  _.forEach(data, async (value) => {
    const day = value.day;
    promos[day] = value;
  });

  return promos;
});

console.log(dataPromo);

It took me a couple of tries to figured out and accepted that maybe mongoose .find() won’t allow you to modify the return data. So moved the _.forEach function outside of the mongoose find() callback.

const queryPromo = Object.assign({ 'foreign_key' : req.params.id });
const dataPromo = await Promo.find(queryPromo, function(err, data) {
  if (err) return [];
  return data;
});


let promos = {};
if (!_.isEmpty(dataPromo)) {
  promos = {};
  _.forEach(dataPromo, async (value) => {
    const day = value.day;
    promos[day] = value;
  });
}

console.log(promos);

I hope this one helps you. Chow!