How to build a conditional query in Mongoose?

后端 未结 3 1737
生来不讨喜
生来不讨喜 2020-12-29 13:46

The following code works with no querystrings or one querystring only. In other words, simply going to /characters returns all

3条回答
  •  情话喂你
    2020-12-29 14:38

    I am using destructing of objects for this task.

    const filter = req.query.filter ? { _id: { $in: req.query.filter.split(',') } } : {};
    const category = req.query.category ? { category: req.query.category } : {};
    // more variables that you need and are empty objects if don't exist
    
    const all = await Post.find({ ...filter, ...category }).exec();
    

提交回复
热议问题