[英]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.大家好,过去 16 小时我正在尝试使用 mongoose 实现此搜索,但不幸的是,无论我尝试什么都没有用。 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此外,例如当我在搜索“地址 1”中编写以获取结果时
address 1,district 1, Prague address 1,district 3, Brno地址 1, 区 1, 布拉格 地址 1, 区 3, 布尔诺
I should look similar like https://www.zillow.com search我应该看起来像https://www.zillow.com搜索
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
.在这种类型的场景中,您希望将搜索输入与任何字段匹配,您必须使用
$or
聚合而不是$and
。 Because you want to match input to be either city or district or address.因为您希望将输入匹配为城市或地区或地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.