简体   繁体   中英

Executing multiple Mongoose queries

I'm using node and mongoose to run queries against my mongodb. I have a set of 3 queries that I'm running as follows :

company.find({ 'shortName': eval("/" + req.params.query + "/i"), logoFileName : {$exists : true} }, function(err, b){
        if(err){
            console.log('brand query not found! ' + err);
            res.send(500, "Something broke!")
        }
        else{
            console.log("length of b : " + b.length)
            if(b.length>1){
                res.render('index', {
                    potentialBrands : b
                })
            }
            else{
                var brandResults  = b[0];   


            var industryQuery = company.find({GICSIndName: eval("'"+brandResults.GICSIndName+"'")}).sort({marketCap: -1}).limit(10);

            industryQuery.exec(function(err, industry){
                if(err){
                    console.log("There was an error! : " + err)
                    res.send(500, "Something broke!")
                }
                //if the colors have yet to be defined
                if(typeof brandResults.associatedColors[0] !== 'undefined'){
                    var colorQuery = company.find({'associatedColors.colorFamily': eval("'" + brandResults.associatedColors[0].colorFamily + "'") });

                    colorQuery.exec(function(err, colors){
                        if(err){
                            console.log("There was an error! : " + err)
                            res.send(500, "Something broke!")
                        }
                        console.log(colors);
                        res.render('brand',{
                            brandResult : brandResults,
                            industryResult: industry,
                            colorResult: colors,
                            queryName : req.params.query
                        });
                    })
                }
                else{
                    res.send(500, "Something broke!")
                }
            })

My current structure seems rather inefficient and I was wondering if there is something within mongo or mongoose that is built for handling such queries.

I suggest taking a look at Promises.

http://mongoosejs.com/docs/api.html#promise_Promise

It also seems like your 2 of queries can run async, you can use Q to run them together:

https://npmjs.org/package/mongoose-q

For organizational purposes (ie,. making the code more readable), there are options like async and streamline .

But to address your question about efficiency, you can offload it to mongo, but unfortunately to be able to do things like querying based on values in the document, you have to rely on the mongo aggregation framework or map-reduce , which may be overkill since they aren't exactly simple.

Just use async

async.waterfall([

    function(wcallback){

      return wcallback(null, req.params.query);

    },

    function(query, wcallback){

       company.find({ 'shortName': eval("/" + req.params.query + "/i"), logoFileName : {$exists : true} }, function(err, b){
         if(err || !b || b.length == 0) return wcallback(err || true);
         else if(b.length == 1) return wcallback(null, b[0]);
         else....

    },

    function(brandResults, wcallback){

        company.find({'associatedColors.colorFamily': eval("'" + brandResults.associatedColors[0].colorFamily + "'") }, function(err, b){
           .....
           return wcallback(null, ...);
    }

  ], function(err, result){

     // final callback
     if(err) ... else ...

  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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