0

I am trying to fetch data from two different collection category_types and categories. Each category has a parent category_type. So i want to push the category_type details when finding all the categories, in every index of category.

Here is my code

exports.findAllWithParentChild = (req, res) => {
    let resData = [];
    Models.Category.find()
    .then(data => {
        data.forEach(element => {
             Models.CategoryType.findById(mongoose.Types.ObjectId(element.categorytype_id))
             .then(catType => {
                resData.push(element, {'category_type' : catType})
            })
        });
        console.log(resData)
        res.send({
            response: true,
            message: 'Categories fetched successfully.',
            data : resData
        });
    }).catch(err => {
        res.status(500).send({
            response: false,
            message: "Some error occurred while retrieving."
        });
    });
};

If i console resData within the loop then it prints data correctly, outside of loop it is empty and also send empty response.

I want the format should look like this

[{   
    _id: 5cb2f300ce34a53c9070ca9c,
    title: 'edeededede',
    description: 'dededededed',
    slug: 'ededede',
    categorytype_id: 5cb2f247db13d03360a3a3c5,
    user_id: 'dedede',
    created_at: 2019-04-14T08:44:48.516Z,
    updated_at: 2019-04-14T08:44:48.516Z,
    __v: 0 ,
    category_type:
     { 
       _id: 5cb2f247db13d03360a3a3c5,
       title: 'trgtrgtrg',
       description: 'trgtrgtrg',
       slug: 'trgtrgtr',
       user_id: 'gtrgtrgtr',
       created_at: 2019-04-14T08:41:43.935Z,
       updated_at: 2019-04-14T08:41:43.935Z,
       __v: 0
     }
}]

If there is any better way let me know.

Eddie
  • 26,593
  • 6
  • 36
  • 58
Amalendu Kar
  • 458
  • 1
  • 6
  • 17
  • 2
    Your `console.log` is executed before `forEach` finishes. – Ivan Rubinson Apr 14 '19 at 15:45
  • 1
    Why not use [`async`/`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)? – Ivan Rubinson Apr 14 '19 at 15:45
  • 2
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Apr 14 '19 at 15:45

1 Answers1

0

The problem here is, that your console.log is executed before your async function (inside then statement). You should consider using async/await statements as shown below.

exports.findAllWithParentChild = (req, res) => {
    let resData = [];
    Models.Category.find()
    .then(data => {
        data.forEach(async element => {
             let catType= await Models.CategoryType.findById(mongoose.Types.ObjectId(element.categorytype_id));
             resData.push(element, {'category_type' : catType});                 
        });
        console.log(resData)
        res.send({
            response: true,
            message: 'Categories fetched successfully.',
            data : resData
        });
    }).catch(err => {
        res.status(500).send({
            response: false,
            message: "Some error occurred while retrieving."
        });
    });
};
tadej
  • 701
  • 1
  • 5
  • 22