【发布时间】:2019-01-17 21:28:31
【问题描述】:
我一直在查看有关堆栈溢出的其他一些答案,并尽我所能。我了解到我需要创建一个文本索引来定义我的架构,我这样做了:
productSchema.index({'title': 'text', 'address.city': 'text'});
如果我只搜索 1 个字段,即:标题,那么我会得到预期的结果。
Product.find( { $text: { $search: searchTerm } } )
但是在尝试同时按标题和城市进行搜索时,我的查询出现了问题。
Product.find( { $text: { $search: searchTerm }, $text: { $search: city } } )
我没有看到任何错误,但我没有得到任何结果,即使我知道我的查询应该有结果。我不确定是不是因为地址是一个对象(根据我在 Compass 中看到的)
这就是我使用 Mongoose 在我的架构中定义它的方式
address: {
city: {type: String, required: true }
},
如果我这样做:
Product.find().and([{ title: searchTerm }, { 'address.city': city }])
它几乎可以工作。但我必须输入产品的确切名称。如果产品被称为“橡皮鸭”并且我输入“鸭子”我没有得到任何结果。如果我输入“一只橡皮鸭”并选择它列出的城市,我会得到一个结果。
我也试过这个:
Product.find( { $and: [ {$text: { $search: searchTerm }}, { address: {city : city } } ] } )
这似乎可行,但可能需要改进!
【问题讨论】: