[英]Mongoose search for all fields with $regex
Say, for instance, I have the following model: 比方说,我有以下模型:
var advertise = mongoose.Schema({
username: String,
text: String,
locations: Array,
days: Array,
phone: Object,
images: Array,
age: Number,
height: String,
sex: String,
categories: Array,
targetAudience: Array,
prices: Array,
creator: String,
hairColor: Object,
eyeColor: Object,
breastSize: Object,
bodyType: Object,
advertiseType: Object,
created: {type: Date, default: Date.now},
is_active: {type: Number, default: 0},
order_id: String
});
Now I have a value called searchString
. 现在我有一个名为
searchString
的值。 Is there a way I can search for all fields with the searchString
? 有没有办法用
searchString
搜索所有字段?
Right now I only know to do this with the $or
key. 现在我只知道使用
$or
key执行此操作。 However, this would be impractical. 但是,这是不切实际的。
Like the following: 如下:
mongoose.models.advertise.find({$or: [{'username': {'$regex': searchString}}]}, function (err, advertise) {
res.json(advertise)
})
Note I'm using Node.js
注意我正在使用
Node.js
If you have the ability to create a $text index : 如果您能够创建$ text索引 :
var advertise = mongoose.Schema({
username: String,
text: String,
locations: Array,
days: Array,
phone: Object,
images: Array,
age: Number,
height: String,
sex: String,
categories: Array,
targetAudience: Array,
prices: Array,
creator: String,
hairColor: Object,
eyeColor: Object,
breastSize: Object,
bodyType: Object,
advertiseType: Object,
created: {type: Date, default: Date.now},
is_active: {type: Number, default: 0},
order_id: String
});
advertise.index({ username: 'text', text: 'text', height: 'text', sex: 'text', creator: 'text', order_id: 'text' });
To perform a search : 要执行搜索:
mongoose.models.advertise.find({ $text : { $search : searchString } }, function (err, advertise) {
res.json(advertise)
})
I didn't tried for real do not hesitate to correct potential errors. 我没有真正尝试过,不要犹豫,纠正潜在的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.