如何从数据库中按文本索引搜索多个字段

时间:2016-06-21 19:22:11

标签: node.js mongodb mongoose

在这个product.model.js文件中我有我的架构,我的问题是每当我搜索任何东西时,让我们说“牛仔裤”然后它应该返回所有3个字段中用product_name,product_code和product_description编写的牛仔裤

Here is product.model.js
var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;


var ProductSchema   = new Schema({
product_name : {type: String, required: [true, 'Please give a product name'], unique: true}, //R U
product_code : {type: String, required: [true, 'Please give a product code'], unique: true},  //R U 
product_description : {type: String},    //"New Product for New Generation",
product_image : {type: String},//"default.jpg",
product_category : {type: String, required: [true, 'Please mention the category here']},//"Online", R 
product_price : {type: Number, required: [true, 'Please give a product price']},//700.00, R
product_tax : {type: Number, required: [true, 'Please write a product tax here']},//15, R 
product_status : Boolean, //true
product_current_stock : [],
product_min_quantity : {type: Number, min: [10, 'Too few products'], required: true},//10, R
product_unit : {type: String, required: [true, 'Please give a product unit']},//"Nos" R 
            });
ProductSchema.index({ product_name: "text" , product_code: "text", product_description: "text" });
            module.exports = mongoose.model('Product', ProductSchema);
and app.js
app.get('/product/search/:query', function(req, res){

var e = Product.find({ $text: { $search: req.params.query } },
         { score: { $meta: 'textScore' } }).
        sort({ score: { $meta: 'textScore'}}).
        exec(function(err, product)
        {
            if(err){
                    res.send(err)
                    }else{
                        res.status(200).json([{"Success": "true"}, {"Message": "Showing searched products"}, {"Total": "fail"}, {"Item": product} ]);
                        }
                    })
        })

0 个答案:

没有答案