你好,我仍然是Nodejs和MongoDB的初学者。当我如下所示运行res.render()函数时,我得到了2个控制台日志,首先是来自mongodb find查询的正确结果,其次是null。如果我删除res.render(),则它只能与一个console.log()输出一起正常工作,而不能与第二个null一起工作。
router.get('/:areaslug', (req, res) => {
// Query results
let areavar = {}
return client.db("AwesomeApartments")
.collection("areas")
.findOne({slug: req.params.areaslug
})
.then((datadb) => {
// first time shows correct results next it shows null
console.log(" bug-testing : "+JSON.stringify(datadb));
//storing result of first query to my object
areavar = datadb;
return client.db("AwesomeApartments")
.collection("apartments")
.find({area:datadb._id})
.toArray()
})
.then((apartmentdb) => {
// Storing results of second query
areavar.apartments = apartmentdb;
//removing this solves the issue
return res.render('area',areavar);
}).catch(err =>
{
console.log(err);
return;
})
});
对于那些在这里找到路的人,浏览器正在生成两个get请求。第一个用于查询,第二个用于favicon.ico。处理favicon.ico请求解决了此问题。