简体   繁体   中英

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. 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".

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. But how can I push the productIds and corresponding quantities to that single order document with "userId":"88888"? I need to be able to create a function in mongodb /nodejs to create a new order 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:

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 }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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