How do I send multiple queries from one endpoint with Express?

后端 未结 2 568
春和景丽
春和景丽 2021-01-23 13:26

I am trying to query my database several times and construct an object which stores every response from my database in a field. Here is my code:

router.post(\'/s         


        
2条回答
  •  青春惊慌失措
    2021-01-23 13:43

    You can do it with Promises

    router.post('/search', (req, res) => {
        var collection = db.get().collection('styles');
        // Create promise for "make.name" query
        let firstQuery = new Promise((resolve, reject) => {
            collection.distinct('make.name', (err, docs) => {
                if (!err) {
                    resolve(docs);
                } else {
                    reject(err);
                }
            });
        });
        // Create promise for "model" query
        let secondQuery = new Promise((resolve, reject) => {
            collection.distinct('model', (function (err, docs) {
                if (!err) {
                    resolve(docs);
                } else {
                    reject(err);
                }
            }))
        })
        // Run both queries at the same time and handle both resolve results or first reject
        Promise.all([firstQuery, secondQuery])
            .then((results) => {
                res.send({ "make.name": results[0], "model": results[1] });
            })
            .catch((err) => {
                // Catch error 
                res.send({});
            });
    });
    

    Also you can use destructuring in callback functions like that:

    Promise.all([firstQuery, secondQuery])
        .then(([makeName, model]) => res.send({ "make.name": makeName, model }))
    

    UPD: If you have a bunch of collection to request you can create an array of collections name, map it to promise requests and handle with Promise.all, for example

    let collections = ["firstCollection", "secondCollection", "nCollection"];
    let promises = collections.map((collectionName) => {
        return new Promise((resolve, reject) => {
            collection.distinct(collectionName, (err, docs) => {
                if (!err) {
                    resolve(docs)
                } else {
                    reject(err);
                }
            });
        })
    });
    Promise.all(promises)
        .then(results => {
            // Do what you want to do
        })
        .catch(error => {
            // or catch 
        });
    

提交回复
热议问题