Why can't external variables be fetched within the $where of mongodb?

in the following code, external variables cannot be fetched within $where, for example, req, prompts that req is not defined. Why is the solution?

router.get("/get",(req,res)=>{
    comments.find({$where:function(){
      return this._id===req.query.id
    }},{email:0}).exec((err,docs)=>{
      if(err){
        res.json({
          sts:0,
          data:err
        })
        return
      }
      res.json({
        sts:1,
        data:docs
      })
    })
})
Mar.19,2022

I answered my own question. Although I still don't know why $where is written as a function, it can't get the value of a variable outside the function, but it can be changed to a string

.
`this._id==='${req.query.id}'`

you can get it, and if any great god knows why the function can't get the value, it can't solve the puzzle. Thank you!

Menu