使用nodejs在整个集合(mongodb)中搜索

时间:2016-05-09 17:26:46

标签: angularjs node.js mongodb express mongoose

我想使用Nodejs在Mongodb集合中实现整个搜索功能。 在整个集合中,我应该传递给SaleModel.find()如此给定的值搜索?

以下是我试过的内容,但它只搜索product_name,我也想搜索sale_amount,sale_person,department_name。

我怎么能这样做?

SaleModel.find({'product_name': 'searched value'});

架构:

var saleSchema = mongoose.Schema({
    product_name:{ type:String, required:true},
    sale_amount:{ type:Number, required:true },
    sale_date:{ type:Date, default:Date() },
    sale_person:{ type:String, required:true }, 
    department:{ type:mongoose.Schema.Types.ObjectId, ref:'department' },
});
module.exports = mongoose.model('sale', saleSchema);

1 个答案:

答案 0 :(得分:0)

我会更加清晰,下面的示例使用async.parallel承诺 Mongoose.Query

function list(req) {

    // promise or callback works as well
    return new Promise(function(resolve, reject){

        // npm install async --save
        var async = require('async'); 

        // some validation can be applied
        var page = {
            skip: req.query.start || 1,
            limit: req.query.length || 25,
            text: req.query.search || ''      // <== this is new property!
        };

        // reuse Mongoose.Query with search by regex
        var Query = Models.SaleModel.find({
            product_name: new RegExp(page.text, "i")
        });

        // run without waiting until the previous function has completed
        async.parallel([
            function(){
                Query.count(callback); // <== count
            },
            function(){
                Query.skip(page.skip).limit(page.limit).exec('find', callback); // <== items
                // or the below one should also work, just don't remember
                // Query.skip(page.skip).limit(page.limit).exec(callback);
            }
        ]), function(err, results){
            if(err){
                reject(err);
            } else {
                resolve({
                    count: results[0],
                    data: results[1]
                });
            }
        });
    });
}