Steps for generating an order from a shopping cart in Mongoose and removing the cart from the system

In my current task, I need to:

  1. Generate an order based on the items in my shopping cart
  2. Include the relevant object attributes in the order response based on the selection in the "select" option
  3. Ultimately, I aim to clear or delete the cart once the order is created

Although I have attempted the following steps, I have encountered several issues:

  1. The response returned is not populated even though the prevProductsQuantity constant contains data
  2. Despite creating the function cartClear to delete the cart document based on its ID, the function is not functioning as expected
  3. I seem to be able to create duplicate orders, suggesting a need for conditional handling, but I am unsure where to implement it

Desired response structure:

{
"success": true,
"data": {
  "_id": "607ed5c425ae063f7469a807",
  "userId": "6071aed0ed7ec9344cf9616c",
  "productsQuantity": [
    {
      "_id": "607f2507994d5e4bf4d91879",
      "productId": {
        "productRef": "463b8bb7-6cf6-4a97-a665-ab5730b69ba2",
        "productName": "table",
        "brand": "boehm llc",
        "price": 713,
        "__v": 0,
        "createdAt": "2021-04-09T18:31:43.430Z",
        "updatedAt": "2021-04-09T18:31:43.430Z"
      },
      "quantity": 2,
      "updatedAt": "2021-04-21T15:12:51.894Z",
      "createdAt": "2021-04-21T15:12:51.894Z"
    }
  ],
  "__v": 0
}

++ Clearing the Cart ++

Current response received:

{
  "success": true,
  "data": {
    "state": "pending-payment",
    "_id": "6080507a0c758608d0dc585c",
    "userId": "6071aed0ed7ec9344cf9616c",
    "totalPrice": 1426,
    "productsQuantity": [
      {
        "_id": "607f2507994d5e4bf4d91879",
        "productId": "60709d8f24a9615d9cff2b69",
        "quantity": 2,
        "updatedAt": "2021-04-21T15:12:51.894Z",
        "createdAt": "2021-04-21T15:12:51.894Z"
      }
    ],
  "createdAt": "2021-04-21T16:19:06.056Z",
  "updatedAt": "2021-04-21T16:19:06.056Z",
  "__v": 0
}

** Issue with Cart Deletion **

Below is the code I have implemented for this process.

Any suggestions or guidance would be highly appreciated

router.post('/', [isAuthenticated], async (req, res, next) => {
  try {
    const cart = await CartModel.findOne({ userId: req.user }).populate({
      path: 'productsQuantity.productId',
      select: {
        price: 1,
        brand: 1,
        productName: 1,
        productRef: 1,
        pictures: 1
      }
    });

    const prevProductsQuantity = cart
      .get('productsQuantity')
      .map((el) => el.toObject());

    const totalPriceByProduct = prevProductsQuantity.map(
      (product) => product.productId.price * product.quantity
    );
    const totalPrice = totalPriceByProduct.reduce(function (a, b) {
      return a + b;
    });

    const result = await OrderModel.create({
      userId: req.user,
      totalPrice: totalPrice,
      state: 'pending-payment',
      productsQuantity: prevProductsQuantity
    });

    const cartClear = (id) =>
      CartModel.deleteOne({
        _id: id._id
      });

    res.status(200).json({
      success: true,
      data: result
    });
    cartClear(`${cart._id.toString()}`);
  } catch (error) {
    next(error);
  }
});

Answer №1

Don't forget to include async and await when resolving the deleteOne promise.

const clearCart = async (id) =>
  CartModel.deleteOne({
    _id: id
  });

 await clearCart(`${cart._id.toString()}`)
 res.status(200).json({
   success: true,
   data: result
 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with the installation of blueimp-file-upload-expressjs

Attempting to set up installation for blueimp-file-upload-expressjs using this command: npm i --save blueimp-file-upload-expressjs Encountering the following error: npm WARN package.json [email protected] No repository field. npm WARN package.json ...

Preserve the values of checkboxes throughout the entire website by utilizing localStorage

Example A functionality in the example allows users to add images to a container by clicking on checkboxes. However, there is an issue where when a checkbox is checked on one page to store an image, and then another checkbox is checked on a different page ...

The selected element does not support the addition of setSelectionRange

I have encountered an error while trying to add the "setSelectionRange" method to an input element that I selected using "getElementById". The error message states that "property 'setselectionrange' does not exist on type 'htmlelement'" ...

Selenium's WebDriver getAttribute function can return an object of type "object",

In my selenium script, I aim to extract text from table columns following the cell with the specified value. Although the script functions, I encounter an issue where getText() returns [Object Object] in my node.js console. I have attempted various method ...

Utilizing Angular 2's *ngFor to conditionally wrap elements can be compared to organizing a layout with three columns in a Bootstrap row, then starting a

Currently I am facing a challenge with using *ngFor and it has me puzzled. My goal is to incorporate UIkit, but the same concept would apply to Bootstrap as well. <div *ngFor="let device of devices" > <div class="uk-child-width-expand@s uk-te ...

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

populating a multi-dimensional array using a "for" loop in Javascript

It appears that JavaScript is attempting to optimize code, causing unexpected behavior when filling a multidimensional array (largeArr) with changing values from a one-dimensional array (smallArr) within a loop. Take the following code for example: largeA ...

Nested solution object populated with promises

Looking for a solution similar to the npm libraries p-props and p-all, but with the added functionality of recursively resolving promises. const values = { a: () => Promise.resolve(1), b: [() => Promise.resolve(2)], c: { d: () =&g ...

Can a Vue computed property return a promise value?

I have a specific computed property in my code that triggers an API request and retrieves the required data: async ingredients() { const url = "/api/ingredients"; const request = new Request(url, { method: "GET", credentials: "same-or ...

What is the best method to trigger a bootstrap modal window from a separate component in Angular 8?

I have successfully implemented a bootstrap modal window that opens on a button click. However, I am now facing difficulty in opening the same modal window from a different component. Below is the code I have tried: <section> <button type=&quo ...

Displaying HTML content in an AngularJS application using ExpressJS

Currently using Angular on the front end and Express.js with MongoDB on the backend. In my server.js file of the Express application, I am listening on port 3000. var server = app.listen(3000, function () { console.log('Server listening at http: ...

Running function without the need to click on 'li' element

In the process of developing a simple guessing game, my aim is to allow users to click on a number and have that number stored as userAnswer, while the computerAnswer is a randomly generated number between one and ten. Despite setting the setVariables() f ...

JavaScript treats string as a primitive value

When it comes to JavaScript, a String is considered a primitive value. However, it can also be treated as a String object. In programming terms, a primitive value refers to a value assigned directly to a variable. This raises the question: var d = "foo"; ...

Mastering the Art of Defining JavaScript Classes in React-Native

In my React Native project, I am faced with a situation where I need to create a new class: class customClass { email: string; name: string; constructor() { setUser(fbid: string, token: string): boolean { To keep things organized, I decide ...

Server encountering issues when locating environment variables in Webpack/Express configuration

Having an issue with my Express/React app's server-side rendering setup using Webpack. I'm encountering a build error related to environment variables that I need in my Express server script. In my index.js server script, I have defined the vari ...

What are some strategies for retrying an Apollo Client query after a failure?

When working with Next.js server-side rendering (SSR), I often encounter a query failure on the first try due to the backend not being fully ready. In such cases, I would like to retry the fetch using ApolloClient. const PREVIEW = { query: MY_PREVIEW_ ...

Adding External JS Files to a Node.js Project

I recently discovered how to incorporate a JS file into Node JS. However, I am facing an issue with two JS files in particular - hashing.js and encoding.js. Within encoding.js, I have the following code: exports = exports || {}; exports.encoding = encodi ...

Explaining the jQuery $.post method

After a thorough search, I finally discovered the importance of adding return false; at the end of my JQuery code for posting data. Without it, my code wasn't functioning as expected. As a beginner in JQuery, I would appreciate some insights into the ...

Safeguard sub-pages with Passport Local if the user has not logged in

I attempted to follow a tutorial on local authentication with Passport and Express, but I am encountering difficulties in protecting my pages for users who are not logged in. My goal is to redirect them to the login page. I experimented with creating midd ...

Prevent unauthorized AJAX requests from external sources within the Node application

I am looking for a way to prevent AJAX requests from being made outside of my application. I need to ensure that the response is not sent when the AJAX request is initiated from external sources, even if the URL is copied and pasted into a browser. My te ...