繁体   English   中英

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

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

尝试使用 nodejs 和 mongoose 合并多个集合但不工作。任何人都可以找到解决方案。

收到此错误:

错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头

产品.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');

产品.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 来电

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

您的代码有几个问题,我将只关注如何组合多个查询的结果,这实际上是如何处理一般的异步 function 结果。 但是你也应该注意这里提到的其他问题

  • 循环调用res.json() ,你肯定会得到“Headers already sent”错误
  • res.json()的结果放入数组中; res.json() 返回ServerResponse ,这与我们想要的无关。
  • 接受用户输入(集合名称)并将它们直接传递给数据库操作是危险的。
  • 处理异步函数:
// 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()

请注意,您只能在async function 中使用await ,因此您必须像这样修改 function

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

更多关于array.flat()

暂无
暂无

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

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