簡體   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