我正在下面模型中 location
对象上的 API 上设置 mongo db 测试搜索。
尝试在数据库中设置文本搜索时出现错误,如下所示。请问可能是什么问题?
const mongoose = require('mongoose')
const placeSchema = new mongoose.Schema({
owner: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
location: {
country: {
type: String,
required: true,
},
street: {
type: String,
required: true,
},
city: {
type: String,
required: true,
},
state: {
type: String,
required: true,
},
zip: {
type: String,
required: true,
}
},
price: {
currency: {
type: String,
required: true
},
amount: {
type: Number,
required: true
}
}
img: {
type: Boolean,
required: false,
default: false
},
phone: {
code: {
type: String,
required: true
},
number: {
type: String,
required: true,
}
},
})
placeSchema.index({ location.country: 'text', location.street: 'text', location.city: 'text', location.state: 'text', location.zip: 'text' })
const Place = mongoose.model('Place', placeSchema)
module.exports = Place
答案 0 :(得分:2)
你应该试试这个辅助函数。
您可以将搜索词作为第一个参数传递,将用于搜索的字段数组作为第二个参数传递。
module.exports.searchHelper = function (searchWord, fields) {
let orArr = [];
let search = searchFiled.split(" ");
fields.forEach((element1) => {
search.forEach((element) => {
orArr.push({ [element1]: { $regex: new RegExp(element, "i") } });
});
});
return { $match: { $or: orArr } };
};
现在你必须在管道中聚合它:
let fieldsArray = ['location.country','location.city','location.state'] //as per your need
let pipeline = [];
pipeline.push(searchHelper(searchWord, fieldsArray));
const results = await Place.aggregate(pipeline);