[英]How to get nested values from an object and push to another newly created object/document in MongoDB?
我还在学习 NodeJs 和 MongoDB。 如果这对某些人来说可能是一个简单的问题,我很抱歉。 我正在做一个项目,但我被卡住了,不知道该怎么做。
我创建了 2 个 collections:“购物车”和“订单”。
在购物车文档中,我有这个(示例):
/* 1 */
{
"_id" : "11111",
"userId" : "88888",
"productId" : "oranges",
"quantity" : 10,
}
/* 2 */
{
"_id" : "22222",
"userId" : "88888",
"productId" : "apples",
"quantity" : 5,
}
/* 3 */
{
"_id" : "33333",
"userId" : "77777",
"productId" : "grapes",
"quantity" : 5,
}
在订单集合中,我有这个:
/* 1 */
{
"userId": "88888",
"products": [{
"productId": xxxxxx ,
"quantity": xx
}],
"totalAmount": xx
}
现在我使用Cart.find({userId: 88888})
查看所有 userId 为 8888 的“购物车”。它给了我一个 object 和所有这些购物车。 但是如何将 productIds 和相应的数量推送到具有“userId”:“88888”的单个订单文档? 我需要能够在 mongodb /nodejs 中创建 function 以创建新订单 object。 我希望能够得到这样的东西:
/* 1 */
{
"userId": "88888",
"products": [
{
"productId": "oranges",
"quantity": 10
},
{
"productId": "apples",
"quantity": 5
},
],
"totalAmount": xx
}
谢谢你。
您可以做的是返回用户产品并使用$push
和$each
将所有产品添加到订单中:
const userProduct = await Cart.find({ userId: 88888 }).select({ 'productId': 1, 'quantity': 1, '_id': 0, });
const updatedOrder = await Order.findOneAndUpdate(
{ userId: 88888 },
{ $push: { products: { $each: userProduct } }},
{ new: true }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.