Javascript 如何在Mongoose中修改生成的查询而不影响实际文档?
状态(截至2020年5月6日):已解决,请参阅下面确定的答案 尽管我们目前正经历全球危机,但我希望一切顺利。我目前正在做一个学校网站项目,需要呈现分配给我的特定功能。我正在使用猫鼬和特快车,以及用于模板制作的把手。请参阅下面随附的模型模式和说明 集合模型-集合AJavascript 如何在Mongoose中修改生成的查询而不影响实际文档?,javascript,java,json,mongodb,mongoose,Javascript,Java,Json,Mongodb,Mongoose,状态(截至2020年5月6日):已解决,请参阅下面确定的答案 尽管我们目前正经历全球危机,但我希望一切顺利。我目前正在做一个学校网站项目,需要呈现分配给我的特定功能。我正在使用猫鼬和特快车,以及用于模板制作的把手。请参阅下面随附的模型模式和说明 集合模型-集合A var collegeSchema = new Schema({ shortName: {type: String}, //value that I intend to synchronously query its occu
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)时它都返回一个值,但当它被推送时,它会变成[]。希望你能帮助我实现我的目标。谢谢 查询是异步解析的,您必须找到一种方法等待所有查询完成,以确保您拥有所需的所有数据 解决此问题的一种方法是使用(Node.js>=7.6.0)
app.get('/testCount',async函数(req,res){//注意async关键字
const collegeRes=await collegeModel.find({}).lean().exec()//.exec()返回一个承诺,因此可以“wait”它。
const resultPromises=collegeRes.map(异步college=>{//arrow函数与此上下文中的函数等效
const professorCount=等待professorModel.countDocuments({college:college.shortName})
college.count=教授count
返回学院
})
const collegeObject=wait Promise.all(resultPromises)
console.log(collegeObject)
})
从bluebird
可以使用更具可读性的工具库,或者您也可以使用其他promise实用程序库
const collegeObject=wait Promise.map(学院,学院=>{
const professorCount=等待professorModel.countDocuments({college:college.shortName})
college.count=教授count
返回学院
})
console.log(collegeObject)
您将console.log(document.count)放在哪里。countDocuments操作是异步的,如果不跟踪计数,您将不知道最后一个文档将在何时被推送。如果您的环境支持,我建议您使用asyc/await
。我将它添加到第一个}之后
就像我说的,countDocuments
是异步的,您将回调传递给它,它将在稍后执行。当您在那里console.log
时,将不会执行回调。尝试使用async/await
和Promise
代替teadhi@TheeSritabtim,谢谢您的帮助!我到底要怎么做?很抱歉,我只是js编码和使用MongoDb/MongooseHi的初学者,谢谢!你的回答解决了我的问题,而且你能如此清楚地向我解释。祝你好运!