sql >> Database >  >> NoSQL >> MongoDB

Zoek in de hele collectie (mongodb) met nodejs

Ik zou zeer schoner willen schrijven, onderstaand voorbeeldgebruik async.parallel , Belofte en 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]
                });
            }
        });
    });
}



  1. Hoe $unset en $set in combinatie te gebruiken in mongoDB

  2. MongoDB db.copyDatabase mislukt bij ongeautoriseerde

  3. Snellere manier om alle sleutels en waarden in redis db . te herhalen

  4. zoektijd met index> zonder index