Angular中ngFor渲染订单商品属性不显示但console.log正常问题
问题分析
你遇到的核心问题是后端未深层填充OrderItem关联的Product数据:
- 当前路由仅填充了
orderItems的基础数据(如quantity),但OrderItem内的product字段只是指向Product模型的ObjectId,并未从数据库拉取Product的具体属性(name、brand等)。 - console.log能看到product字段是因为它是ObjectId,但前端需要的具体属性并未返回,因此渲染时无法显示。
解决方案
修改后端路由的populate逻辑,对orderItems进行嵌套填充,将关联的Product数据一并拉取:
router.get(`/:id`, async (req, res) => { let order = await Order.findById(req.params.id) .populate('user', 'name') // 嵌套填充orderItems下的product关联数据 .populate({ path: 'orderItems', populate: { path: 'product' } }) if(!order) { res.status(500).json({success: false}) } res.send(order); })
额外检查点
确认OrderItem模型已正确导出,否则mongoose无法识别关联关系:
const mongoose = require ('mongoose'); const orderItemSchema = mongoose.Schema ({ quantity: { type: Number, required: true }, product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' } }) // 新增模型导出语句 exports.OrderItem = mongoose.model('OrderItem', orderItemSchema);
修改完成后,后端返回的order数据中,每个orderItem的product字段会包含完整的Product属性,前端渲染orderItem.product?.name等字段即可正常显示。
内容的提问来源于stack exchange,提问作者ENN9
相关产品推荐
相关产品推荐

