简体   繁体   中英

How to advance mongoose search?

Hello everyone last 16 hours I`m trying to implement this search with mongoose, and unfortunately whatever I try didn't work. Hope someone here will be able to help me.

So I have schema

    const propertySchema = new mongoose.Schema({

    city:{
        type:String
    },
    district:{
        type:String
    },
    address:{
        type:String
    }
});

  const Property = mongoose.model('property',propertySchema);
  exports.module = Property

And this is my collection (demo) data

    {
    "city":"Prague",
    "district":"district 1 ",
    "address":address 1"
},
{
    "city":"Prague",
    "district":"district 1 ",
    "address":address 1"
},
{
    "city":"Ostrava",
    "district":"district 2 ",
    "address":address 2"
},
{
    "city":"Ostrava",
    "district":"district 2",
    "address":address 2"
},                                                                          
{
    "city":"Brno",
    "district":"district 3",
    "address":address 1" //Let`s pretend somehow this address in Bruno exists in Prague too 
},

What I want now is when I write in search "Prague" to get result

Prague

Also when I write for example in search "address 1" to get result

address 1,district 1, Prague address 1,district 3, Brno

I should look similar like https://www.zillow.com search

So far I came up with a lot of idea and this is last (that didn`t work but still I want to share it with you maybe with some modification can make this )

  const all = await Property.find({$and:[{city:{$regex: req.body.tag, $options: 'i'}},{address:{$regex: req.body.tag, $options: 'i'}},{district:{$regex: req.body.tag, $options: 'i'}}]})

In this type of scenario, where you want to match search input to any field you have to put $or aggregation instead of $and . Because you want to match input to be either city or district or address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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