Search code examples
node.jsexpressmongoosepromisemean-stack

Can't manipulate mongoose query result - promise undefined


I'm new to mongoose and promises, so it will probably be something I am not getting clear, here's the thing:

I'm writing my app (MEAN) where I have some web services stacked in my controller to retrieve and get things. I'll make an example.

exports.allowanceCheck = (req, res) => {

  let payload = req.body.excelparam
  let day = getDate(payload[0].data_accesso,1)
  var dummyVar

   return AccessList.aggregate([
    {'$match' : {'id': day}},
    {'$unwind' : '$employees'},
    {
      $group: {
        _id: '$id',
        count: { $sum: 1 }
      }
    }
   ])
  .exec()
  .then((list) => {
    console.log(list) //not working
    res.json(list)
    dummyVar = list
  })
  .catch((err) => {
    res.status(500).send(err)
    
  })

}
console.log(list) //not working
console.log(dummyVar) //not working

The web service works just fine, the client gets his response JSON:

[
    {
        "_id": "200830",
        "count": 2
    }
]

The problem I am getting now is that, if I want to do something with this "list" JSON data, I get an error that I'm trying to manipulate {undefined} stuff. (e.g. everywhere you see //not working - and probably anywhere else) So I can only send the data back and I am not able to manipulate anything.

I tried saving the promise and accessing it, didn't work.

What am I doing wrong?

thank you! :)


Solution

  • You can try the following approach for better understanding of the promise

        exports.allowanceCheck = (req, res) => {
    
        let payload = req.body.excelparam
        let day = getDate(payload[0].data_accesso, 1)
    
        functionAllowanceCheck(day).then((listResponse) => {
            console.log(listResponse) //working
            res.json(listResponse)
        }).catch((listError) => {
            res.status(500).send(listError)
        })
    
    }
    
    const functionAllowanceCheck = (day) => {
        return new Promise((resolve, reject) => {
            AccessList.aggregate([
                { '$match': { 'id': day } },
                { '$unwind': '$employees' },
                {
                    $group: {
                        _id: '$id',
                        count: { $sum: 1 }
                    }
                }
            ]).exec((err, list) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(list)
                }
            })
        })
      }