簡體   English   中英

Mongoose 搜索多個字段

[英]Mongoose search multiple fields

全部,

嘗試使用 NodeJS 和 Mongoose 實現簡單搜索。

不太確定我在哪里 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 }]
        });

基本上,我擁有的是搜索字段,帶有城市和類別過濾器,用戶可以按一個字段(城市、類別或 searchQuery)或全部或兩個字段進行搜索。

Ps 我對 mongoose 比較陌生,所以放輕松;)

謝謝!

請嘗試此查詢

   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