我只是想查找具有相同对象ID但不能正常工作的所有数据
app.get("/admin/phase/:level", function(req,res){
Level.findOne({_id: req.params.level},function(err,onelevel){
console.log(onelevel._id)
Semster.find({level: onelevel._id},function(err,semster){
Module.find({semster: semster._id } , function(err , modules){
console.log(semster)
res.render("semster",{onelevels: onelevel, semsters: semster, modules: modules})})})})});
答案 0 :(得分:0)
我建议您在数据库查询中使用async and await,以便猫鼬有足够的时间查找文档。话虽如此,我将使用try-catch块来响应查询中的错误。
app.get("/admin/phase/:level",async function(req,res){
try{
const onelevel = await Level.findOne({_id: req.params.level});
const semster = await Semster.find({level: onelevel._id});
let modules = [];
for(let i = 0; i < semster.length; i++){
let module = await Module.find({semster: semster[i]._id });
modules.push(...module)
};
res.render("semster",{
onelevels: onelevel,
semsters: semster,
modules: modules})
})
})
})
catch(err){
res.status(500).render("/uhOhPage",{
message: err.message
})
});
答案 1 :(得分:0)
我们通过使用MongoDB Aggregate或对async/await使用循环来解决此问题。我希望您更喜欢使用MongoDB作为首选的最佳方法。
使用JavaScript:
app.get("/admin/phase/:level", async function (req, res) {
Level.findOne({ _id: req.params.level }, function (err, onelevel) {
Semster.find({ level: onelevel._id }, function (err, semsters) {
const modulePromise = semsters.map(semster => Module.find({ semster: semster._id }));
var modules = await Promise.all(modulePromise);
res.render("semster", { onelevels: onelevel, semsters: semsters, modules: modules })
})
})
});
已更新:
app.get("/admin/phase/:level", async function (req, res) {
try {
const onelevel = await Level.findOne({ _id: req.params.level });
const semsters = await Semster.find({ level: onelevel._id });
const modulePromise = semsters.map(semster => Module.find({ semster: semster._id }));
var modules = await Promise.all(modulePromise);
res.render("semster", { onelevels: onelevel, semsters: semsters, modules: modules })
} catch (err) {
//Your Error Handler
}
});
使用Mongo Aggregate:
app.get("/admin/phase/:level", function (req, res) {
Level.findOne({ _id: req.params.level }, function (err, onelevel) {
Semster.aggregate([
{ $match: { level: onelevel._id } },
{ $lookup: { from: "module", localField: "_id", foreignField: "semster", as: "module" } }
], function (err, semsters) {
res.render("semster", { onelevels: onelevel, semsters: semsters})
})
})
});