简体   繁体   English

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

[英]Search in whole collection(mongodb) using nodejs

I want to implement whole search feature in Mongodb collection using Nodejs. 我想使用Nodejs在Mongodb集合中实现整个搜索功能。 What should I pass to SaleModel.find() so given value search in whole collection? 我应该将什么传递给SaleModel.find()以便在整个集合中进行给定值搜索?

Here is what I have try so for but it only search product_name and I want to search sale_amount, sale_person, department_name too. 这是我尝试的方法,但是它仅搜索product_name,我也想搜索sale_amount,sale_person,department_name。

How I can do this? 我该怎么做?

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

Schema: 架构:

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);

I would highly write more cleaner, below sample uses async.parallel , Promise and Mongoose.Query 我会写得更干净一些,下面的示例使用async.parallelPromiseMongoose.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]
                });
            }
        });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM