【发布时间】:2021-12-20 20:43:27
【问题描述】:
我正在使用 NodeJS 和 MongoDB (Mongoose) 开发电子商务网络应用程序。
我有一条可以在购物车中显示产品的获取路线,但我正在苦苦挣扎,因为我需要完成一个功能,然后才能继续执行其余代码。
该函数将项目推送到一个数组,然后我尝试渲染一个传递该数组的视图,但该数组消失为空。
这是我的代码。
router.get('/cart', function (req, res) {
User.findOne({ username: req.user.username }, function (err, doc) {
// This is the array that needs to be passed
const prodAndQty = [];
const prodEntries = Object.entries(doc.shoppingCart);
// This is the function that I need to complete before continuing
prodEntries.forEach(function (entry) {
Product.findOne({ id: entry[0] }, function (err, doc) {
prodAndQty.push([doc, entry[1]]);
});
});
if (err) { console.log(err); }
else {
// If I log here, the array is empty.
console.log(prodAndQty);
if (doc) {
res.render('cart', { doc: doc, qty: prodEntries.length, products: prodAndQty });
} else {
res.render('cart', { doc: null, qty: 0, products: null });
}
}
});
});
如果我在渲染之前记录数组,则数组为空。
此外,在终端中,即使在 Mongoose 查询执行之前,数组也会被记录。
如果我在正在推送的函数中记录数组,则数组已正确填充,但为时已晚,无法使用。
任何帮助将不胜感激。
【问题讨论】:
标签: javascript node.js arrays mongodb mongoose