Javascript Mongoose和express-使用req.query处理.find()的另一个解决方案

Javascript Mongoose和express-使用req.query处理.find()的另一个解决方案,javascript,express,mongoose,Javascript,Express,Mongoose,如您所见,当req.query.priceForDay存在时,where().lt()方法使用req.query.priceForDay值。但当req.query.priceForDay为空时,if()条件返回“1000”号 你们能给我解释一下,只有当priceForDay不为null时,如何告诉mongoose.find()方法使用.where().lt()方法吗?我的解决方案可行,但肯定不是好的编程实践 router.get('/', async (req, res) => { c

如您所见,当req.query.priceForDay存在时,where().lt()方法使用req.query.priceForDay值。但当req.query.priceForDay为空时,if()条件返回“1000”号

你们能给我解释一下,只有当priceForDay不为null时,如何告诉mongoose.find()方法使用.where().lt()方法吗?我的解决方案可行,但肯定不是好的编程实践

router.get('/', async (req, res) => {
  const { brand, priceForDay } = req.query
  try {
    const cars = await Car.find().where('brand').equals(brand).where('priceForDay').lt(priceForDay ? priceForDay : 1000)
    res.status(200).json(cars)
  } catch (error) {
    res.status(400).json(error)
  }
}) 

这是我在这里的第一篇帖子,谢谢你的时间;)

@编辑

我为查询设置了默认值
{brand:'brandname',priceForDay:200}
到目前为止,这是我最好的选择