【发布时间】:2021-06-02 04:42:12
【问题描述】:
我是后端(和一般开发)的初学者。一个问题卡了两个星期。因此,我征求专家意见。 我在 Mongo 中有收藏品 - 订单和物品。我通过 UUID 为他们生成了 ID(我不知道这个信息是否重要)。
Order 对象存储一个项目数组 (items[]),其中包含特定项目的 id 和数量:
Order = {
_id: '123123123123123',
items: [
{
_id: '0001',
quantity: 1
},
{
_id: '0002',
quantity: 4
}
]
}
项目如下所示:
Items = [
{
_id: '0001',
title: 'Pizza',
price: 650,
description: 'Some text'
},
{
_id: '0002',
title: 'Pasta',
price: 500,
description: 'Some text'
}
]
问题是:如何从Items数组中通过id获取Item的数据,并放入Order的Items数组中,将Item的完整信息发送到最前面?包括title,price,和描述。
我尝试使用 for-loops 和 forEach - 但没有结果。对 Order 中的特定项目的调用正在工作(例如这个 Order.items[0]._id),但是在一个循环中(例如这个 Order.items[i]._id)它会给出一个错误,即 Order.items[i]未定义。
控制器:
class testController {
async getTestOrder(req, res) {
try {
const id = req.params.id
const order = await Order.findOne({_id: id})
const items = await Item.find({})
for (let i =0; i < order.items.length; i++){
for (let j = 0; j < items.length; j++){
if(order.items[i]._id === items[j]._id){
order.items.push(items[j]) // don't know how to add new data, leaving quantity
}
}
}
res.send(order)
} catch (error) {
console.log(error);
res.status(404).json({message: 'Order was not found'})
}
}
}
结果,前面我应该得到如下回复:
Order = {
_id: '123123123123123',
items: [
{
_id: '0001',
quantity: 1,
title: 'Pizza',
price: 650,
description: 'Some text'
},
{
_id: '0002',
quantity: 4,
title: 'Pasta',
price: 500,
description: 'Some text'
}
]
}
【问题讨论】:
标签: javascript node.js mongodb express