简体   繁体   English

Mongoose 搜索多个字段

[英]Mongoose search multiple fields

All,全部,

Trying to implement simple search with NodeJS and Mongoose.尝试使用 NodeJS 和 Mongoose 实现简单搜索。

Not really sure where do I go wrong, trying to build up the query like so:不太确定我在哪里 go 错了,尝试像这样构建查询:

const query = Post.find();
if (value.searchQuery && value.city && value.category) {

        console.log("city and category");
        query.where({
            $or: [{ title: value.searchQuery }, { description: value.searchQuery }],
            city: value.city,
            category: value.category
        });

    } else if (value.searchQuery && value.city && !value.category) {

        console.log("No category");
        query.where({
            $or: [{ title: value.searchQuery }, { description: value.searchQuery }],
            city: value.city
        });

    } else if (value.searchQuery && value.category && !value.city) {

        console.log("No city");
        query.where({
            $or: [{ title: value.searchQuery }, { description: value.searchQuery }],
            category: value.category
        });

    } else if (value.searchQuery && !value.city && !value.category) {

        console.log("No city and no category");
        query.where({
            $or: [{ title: value.searchQuery }, { description: value.searchQuery }]
        });

Basically, what I have is search field, with city and category filters and user can either search by one field (city, category or searchQuery) or by all or just two.基本上,我拥有的是搜索字段,带有城市和类别过滤器,用户可以按一个字段(城市、类别或 searchQuery)或全部或两个字段进行搜索。

Ps I'm relatively new to mongoose so take it easy;) Ps 我对 mongoose 比较陌生,所以放轻松;)

Thank you!谢谢!

Please try this query请尝试此查询

   let regex = new RegExp(value.searchQuery,'i');
   { $and: [ { $or: [{title: regex },{description: regex}] }, {category: value.category}, {city:value.city} ] } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM