簡體   English   中英

如何在不影響實際文檔的情況下修改 ZCCADCDEDB567ABAE643E15DCF0974E503Z 中的查詢結果?

[英]How can I modify the resulting query in Mongoose without affecting the actual document?

狀態(截至 2020 年 5 月 6 日):已解決,請參閱下面確定的答案。

盡管我們現在正在經歷全球危機,但我希望一切都好。 我目前正在做一個學校 web 項目,需要渲染分配給我的特定功能。 我正在使用Mongoose和 Express 和 Handlebars 進行模板。 請參閱隨附的 model 架構和下面的說明。

學院模型- 集合 A

var collegeSchema = new Schema({
    shortName: {type: String},  //value that I intend to synchronously query its occurrence with Collection B
    longName: {type: String},
    logo: {type: String},
    contactUs:{
        telNum: {type: String},
        faxNum: {type: String},
        email: {type: String}
    },
    aboutUs: {type: Array},
    visionMission: {type: String},
    coreValues: {type: String},
    goals: {type: String},
    founderBio: {type: String},
    philosophy: {type: String},
    icon: {type: String}
});

教授模型- 集合 B

var professorSchema = new Schema({
    profNumber: {type: Int32},
    college: {type: String},    //value to be compared with shortName
    gender: {type: String},
    profName: {type: String},
    profCourse: {type: String}
});

偽代碼- 要實現的所需邏輯

app.get('/testCount', function(req,res) {
    collegeModel.find({}).lean().exec(function(err,collegeRes){
        var collegeObject = [];
        collegeRes.forEach(function(document){
            professorModel.countDocuments({college:document.shortName}, function(err2,professorCount){
                document.count = professorCount;
                collegeObject.push(document);   //doing a console.log(collegeObject) would return empty objects [].
            });
        });
    });
});

我不知道我做錯了什么,而且我知道 document.count 存在,因為每次我執行 console.log(document.count) 時它都會返回一個值,但是當它被推送時它變成 []。 希望你能幫助我實現我的目標。 謝謝!

您的查詢是異步解決的,您必須找到一種方法來等待所有查詢完成,以確保您擁有所需的所有數據。

解決此問題的一種方法是使用async/await (Node.js >= 7.6.0)

app.get('/testCount', async function(req, res) { // note the async keyword
  const collegeRes = await collegeModel.find({}).lean().exec() // .exec() returns a Promise, so you can `await` it.
  const resultPromises = collegeRes.map(async college => { // arrow function is equivalent to function in this context
    const professorCount = await professorModel.countDocuments({ college: college.shortName })
    college.count = professorCount
    return college
  })
  const collegeObject = await Promise.all(resultPromises)
  console.log(collegeObject)
})

使用bluebirdPromise.map更具可讀性,或者您也可以使用其他 promise 實用程序庫

  const collegeObject = await Promise.map(collegeRes, college => {
    const professorCount = await professorModel.countDocuments({ college: college.shortName })
    college.count = professorCount
    return college
  })
  console.log(collegeObject)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM