简体   繁体   English

如何使用nodejs合并mongodb中的多个集合

[英]How to merge multiple collection in mongodb using nodejs

Trying to merge multiple collection using nodejs and mongoose but not working.Anyone can find solution for this.尝试使用 nodejs 和 mongoose 合并多个集合但不工作。任何人都可以找到解决方案。

Getting this error:收到此错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头

product.model.js:产品.model.js:

    module.exports = mongoose.model('Test1', userSchemaTest1, 'test1');
    module.exports = mongoose.model('Test2', userSchemaTest2, 'test2');
    module.exports = mongoose.model('Test3', userSchemaTest3, 'test3');
    module.exports = mongoose.model('Test4', userSchemaTest4, 'test4');
    module.exports = mongoose.model('Test5', userSchemaTest5, 'test5');

product.controller.js:产品.controller.js:

module.exports.getAllProducts = (req, res, next) => {

    let collection = req.query.collection;
    var newVal = collection.split(',');
    var allP = [];
    var getAllp;
    allP.push(...newVal);
    allP.forEach((element) => {
        let tabledatas = mongoose.model(element);
        tabledatas.find({}, function(err, docs) {
            if (err) {
                console.log('ss' + err);
                return
            }
            getAllp = [...getAllp, res.json(docs)];
        })
    })
    return getAllp; 

}

api call api 来电

http://localhost:3000/api/getAllProducts?collection=Test1,Test2,Test3,Test4,Test5 

There are several issues with your code, I'll focus only on how to combine results of multiple queries, which is actually how to deal with async function results in general.您的代码有几个问题,我将只关注如何组合多个查询的结果,这实际上是如何处理一般的异步 function 结果。 But you should take notes of other issues mentioned here as well但是你也应该注意这里提到的其他问题

  • Calling res.json() in a loop, you'll certainly get "Headers already sent" errors循环调用res.json() ,你肯定会得到“Headers already sent”错误
  • Putting the result of res.json() in to an array;res.json()的结果放入数组中; res.json() returns ServerResponse , which has nothing to do with what we want. res.json() 返回ServerResponse ,这与我们想要的无关。
  • Accepting user inputs (collection names) and pass them directly to the database operations is dangerous.接受用户输入(集合名称)并将它们直接传递给数据库操作是危险的。
  • Handling async functions:处理异步函数:
// models would be a list of model names
const models = collection.split(',')

// map array of model names to array of Promises (result of async operations)
const resultPromises = models.map(modelName => {
  return mongoose.model(modelName).find({}).exec() // use Promise result instead of passing callback
})

// wait on all Promises to be fulfilled and resolved to actual results.
const combinedResults = await Promise.all(resultPromises)
// now you will get a result of this form [[item1, item2, ...], [itemX, itemY, ...], ...]
// but what you want is [item1, item2, ..., itemX, itemY, ...], we can use array.flat()

cont results = combinedResults.flat()

Note that you can only use await in an async function, so you'll have to modify your function like this请注意,您只能在async function 中使用await ,因此您必须像这样修改 function

module.exports.getAllProducts = async (req, res, next) => { // add async keyword
  // ...
}

more on array.flat()更多关于array.flat()

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

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