MongoDB聚合关联产品数据前端读取报undefined错误排查
我使用MongoDB的aggregate聚合查询将订单(Order)与产品(Products)关联,获取指定客户的订单数据。后端返回的数据在console.log中能正常显示产品信息,但前端代码中访问orders[0].Product[0]._id时,出现“Cannot read properties of undefined (reading '0')”错误,订单自身参数可正常使用。已尝试重新发起HTTP请求、重构Mongoose聚合逻辑,但问题仍存在。
后端代码
// GET ORDERS BY CUSTOMER app.post('/getOrderByCustomer', async (req, res) => { const {customerId} = req.body const objectId = new mongoose.Types.ObjectId(customerId); try { //EXEMPLO DE JOIN(aggregate) DE COMPRA(Order) COM PRODUTO(products) const customerOrders = await Order.aggregate([ { $lookup: { from: "Products", localField: "product_id", foreignField: "_id", as: "products" } }, { $match: {customer_id: objectId} } ]); res.send({ status: 'ok', data: customerOrders }) } catch (e) { res.send({ status: 'error', data: e}); } })
前端代码
export default function Orders() { const { customer } = useContext(Context) const [orders, setOrders] = useState<Array<IOrder>>([]) useEffect(() => { if(customer._id !== ""){ http.post('getOrderByCustomer', { customerId: customer._id }) .then(res => (setOrders(res.data.data))) .catch(err => console.log(err)) } },[customer]) return( <> {orders.length === 0 ? "" : <section> <p className={styles.title} onClick={() => console.log(orders[0])}>Show Orders</p> <p>length of orders: {orders.length}</p> {orders[0].Product[0]._id} </section> } </> ) };
Console.log输出的订单数据
{ _id: '649f5dbf6102a6298ca87b63', customer_id: '6455ef2d93e0845caf61b5c8', product_id: '6483b95220b153233677c8e3', data: '2023-06-30T22:56:56.956Z', products: Array(1) } customer_id: "6455ef2d93e0845caf61b5c8" data: "2023-06-30T22:56:56.956Z" product_id: "6483b95220b153233677c8e3" products: Array(1) 0: { _id: '6483b95220b153233677c8e3', imagem: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYwA…QgxrUoAY1qEE/DUrp/w+hmPamURzb6wAAAABJRU5ErkJggg==', titulo: 'Cell Inspiron', descricao: 'Notebook da marca cell, devido a seu processado sn…mas, vem instalado com o sistema Linux de fabrica', preco: '2,899.99', … } length: 1 [[Prototype]]: Array(0) _id: "649f5dbf6102a6298ca87b63" [[Prototype]]: Object
报错信息
ERROR: Cannot read properties of undefined (reading '0')
TypeError: Cannot read properties of undefined (reading '0')
at Orders (http://localhost:3000/main.465c79da82d0b5c47a59.hot-update.js:60:34)
at renderWithHooks (http://localhost:3000/static/js/bundle.js:27873:22)
at updateFunctionComponent (http://localhost:3000/static/js/bundle.js:30755:24)
at beginWork (http://localhost:3000/static/js/bundle.js:32467:20)
at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:17465:18)
at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:17509:20)
at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:17566:35)
at beginWork$1 (http://localhost:3000/static/js/bundle.js:37440:11)
at performUnitOfWork (http://localhost:3000/static/js/bundle.js:36687:16)
at workLoopSync (http://localhost:3000/static/js/bundle.js:36610:9)
问题出在字段大小写不匹配:
- 后端
$lookup配置中,as字段指定的关联结果字段是products(全小写) - 前端代码中错误地使用了
Product(首字母大写)来访问,导致找不到对应属性,进而无法读取索引0
修改前端代码中的访问路径:
// 原代码 {orders[0].Product[0]._id} // 修改后 {orders[0].products[0]._id}
为了避免后续出现类似空值报错,建议添加可选链操作符做安全访问:
{orders[0]?.products?.[0]?._id}
内容的提问来源于stack exchange,提问作者user22163762

