简体   繁体   English

如何从 object 获取嵌套值并推送到 MongoDB 中另一个新创建的对象/文档?

[英]How to get nested values from an object and push to another newly created object/document in MongoDB?

I'm still learning NodeJs and MongoDB.我还在学习 NodeJs 和 MongoDB。 I'm sorry if this might be a simple question for some.如果这对某些人来说可能是一个简单的问题,我很抱歉。 I'm working on a project but I'm stuck and not sure what to do.我正在做一个项目,但我被卡住了,不知道该怎么做。

I created 2 collections: "carts" and "orders".我创建了 2 个 collections:“购物车”和“订单”。

In the carts document I have this (example):在购物车文档中,我有这个(示例):

        /* 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,
        }

In the orders collection I have this:在订单集合中,我有这个:

          /* 1 */
         {
         "userId": "88888",
         "products": [{
              "productId": xxxxxx ,
              "quantity":  xx
          }],
         "totalAmount": xx
         }

Now I used Cart.find({userId: 88888}) to see all "carts" with userId 8888. It gives me an object with all those carts.现在我使用Cart.find({userId: 88888})查看所有 userId 为 8888 的“购物车”。它给了我一个 object 和所有这些购物车。 But how can I push the productIds and corresponding quantities to that single order document with "userId":"88888"?但是如何将 productIds 和相应的数量推送到具有“userId”:“88888”的单个订单文档? I need to be able to create a function in mongodb /nodejs to create a new order object.我需要能够在 mongodb /nodejs 中创建 function 以创建新订单 object。 I'm hoping to be able to get something like this:我希望能够得到这样的东西:

        /* 1 */
        {
          "userId": "88888",
          "products": [
            {
             "productId": "oranges",
             "quantity":  10
            },
            {
              "productId": "apples",
              "quantity":  5
            },
           ],
          "totalAmount": xx
         }

Thank you.谢谢你。

What you could do is return the user products and use $push with $each to add all products to the order:您可以做的是返回用户产品并使用$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM