1

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! :)

EisenRm
  • 45
  • 7

2 Answers2

0

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)
            }
        })
    })
  }
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
  • Introducing the [Explicit Promise Anti-pattern](https://stackoverflow.com/q/23803743/3478010) is going to be more of a hindrance than a help. – Roamer-1888 Sep 04 '20 at 07:02
  • Thanks! now I would like to use the "count" value outside the then clause, since I would like to keep the result, make another query and then respond appending al the data to the same response that the WS call triggered. what should the strategy be? can't still read the dummyVar value :( – EisenRm Sep 04 '20 at 09:23
  • you can try let result = JSON.parse(JSON.stringify(listResponse)) after that you will be able to update value – Pushprajsinh Chudasama Sep 04 '20 at 09:45
  • @vishalpankhaniya can't unfortunately, reply below. any clues? – EisenRm Sep 06 '20 at 14:38
0

@vishalpankhaniya It doesn't unfortunately :( reading it outside of the block is not possible. I tried creating a var inside and before the block and it doesn't change (let shouldn't work all over the allowanceCheck, right?)

exports.allowanceCheck = (req, res) => { 
   ... 
   var lista = JSON.parse(JSON.stringify(listResponse)) 
   ... 
   }).catch((listError) => { 
      res.status(500).send(listError) 
   }) 
console.log(lista) }
EisenRm
  • 45
  • 7