使用nodejs在整个集合中搜索(mongodb) [英] Search in whole collection(mongodb) using nodejs

查看:131
本文介绍了使用nodejs在整个集合中搜索(mongodb)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Nodejs在Mongodb集合中实现整个搜索功能.我应该将什么传递给 SaleModel.find(),以便在整个集合中进行给定值搜索?

I want to implement whole search feature in Mongodb collection using Nodejs. What should I pass to SaleModel.find() so given value search in whole collection?

这是我尝试的方法,但是它只搜索product_name,我也想搜索sale_amount,sale_person,department_name.

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.

我该怎么做?

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

推荐答案

我会写得更加干净,下面的示例使用 async.parallel Promise Mongoose.Query

I would highly write more cleaner, below sample uses async.parallel, Promise and 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]
                });
            }
        });
    });
}

这篇关于使用nodejs在整个集合中搜索(mongodb)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆