我需要提供搜索电子商务网站。其中有一个4级菜单,如。我把它们分成了3个这样的模式
类别架构
category>>subcategory>>product>>subproduct
子类别和产品架构
var categorySchema = new mongoose.Schema(
{
"catname": {type: String, required: true},
}
);
mongoose.model('category',categorySchema);
子产品架构
var productSchema = new mongoose.Schema(
{
"catid": {type: mongoose.Schema.Types.ObjectId, ref: 'category'},
"subcatname": {type: String, required: true},
"product":[
{
"productname":{type:String},
}
]
}
);
mongoose.model('product',productSchema);
我需要提供与用户搜索相对应的var subproductSchema = new mongoose.Schema(
{
"productid": {type: mongoose.Schema.Types.ObjectId, ref: 'products', required: true},
"itemcode": {type: String, required: true},
"itemname": {type: String, required: true/*, index: "text"*/},
"itemdescription": {type: String, required: true},
"itemimgurl": {type: String, required: true},
"mainprice": {type: Number},
"offerprice": {type: Number, required: true},
"unit": {type: String, required: true},
"stock": {type: Number, required: true},
"offertag": {type: String},
"itemprice":[
{
"itemname" :{type: String, required: true},
"unit": {type: String, required: true},
"offerprice": {type: Number, required: true},
"mainprice": {type: Number},
"stock": {type: Number, required: true},
"notify": {type: Number, required: true},
"status": {type: Boolean, required: true},
"itemimgurl": {type: String},
"offertag": {type: String}
}
]
}
);
mongoose.model('subproduct',subproductSchema);
,例如,如果用户使用subproducts
或catname
或subcatname
或productname
进行搜索给出相关的itemname
。我如何用猫鼬实现这一目标?
答案 0 :(得分:1)
这是参考您在评论中提出的问题。
如果您想搜索不完整的查询或单词,我会提供一个小代码,对您有帮助。
var query = req.body.query; //the string you take for search
var filter = {
$or: [
{subcatname: new RegExp('.*' + query, 'i')},
{productname: new RegExp('.*' + query, 'i')},
//similarly you can put more cases
]
}
subproducts.find(filter, function(err, data){
if(err){console.log(err);}
console.log(data);
});