Having trouble adding items to the shopping cart in MongoDB?

Currently, I am in the process of developing a shopping cart system. While I have successfully created one using MongoDB, I seem to be facing an issue when it comes to adding products from the database to the cart. Upon inspection in both the console.log and MongoDB GUI, only an empty items array is displayed. Any assistance on resolving this matter would be greatly appreciated.

const express = require('express');
const Carts = require('../repo/carts');


const router = express.Router();



router.post('/cart/products', async (req, res) => {

  Carts.findById(req.session.cartId, (err, foundCart) => {
    if(err) {
      console.log(err)
    }
    if (foundCart) {
      console.log(foundCart);
      Carts.update( { _id:req.session.cartId }, {
        $push: {
          items: {
            _id: req.body.productId,
            quantity: 1,
          },
        },
      });
    } else {
      if (!foundCart) {
        const newCart = new Carts({
          _id: req.session.cartId,
          items: [],
        });
        newCart.save();
      }
    } 
  });

  res.send('product added to cart!!');
});

module.exports = router;

Here's a glimpse at the carts schema for MongoDB:

const mongoose = require('mongoose');

const cartSchema = new mongoose.Schema({
  _id: String,
  items: [
    { quantity: Number, _id: String,}
  ] 
});

const Carts = new mongoose.model('Carts', cartSchema);

module.exports = Carts;

See the image of how the cart appears in MongoDB Robo3T https://i.sstatic.net/mDBpC.png.

Answer №1

An error is occurring with the findById function. You may want to create a similar function for the update feature and investigate why it's not functioning properly. Additionally, double-check if the id body is being received correctly.

When using Carts.findById(req.session.cartId, (err, foundCart) => {
    if(err) {
      console.log(err) // This error pertains to the findById method, not the update function
    }
    if (foundCart) {
      console.log(foundCart)
      console.log(req.body.productId)
      Carts.update( 
        { _id:foundCart._id }, {
        $push: {
          items: {
            _id: req.body.productId,
            quantity: 1,
          },
        },
      },(err,updatedCart) => {
         if(err){
           console.log(err)
         }
     }
    );
    } else {
      if (!foundCart) {
        const newCart = new Carts({
          _id: req.session.cartId,
          items: [],
        });
        newCart.save();
      }
    } 
  });

  res.send('Product successfully added to cart.');
});

module.exports = router;

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

What is the process for advancing an object in Three.js?

Does anyone know how to advance the position of an object in Three.js? I've been thinking about converting rotation.x, y, z into a vector and manipulating it that way. However, as a beginner, I'm unsure of how to proceed. Any guidance would be g ...

Generate a new array using a single value extracted from an existing array

I'm new to working with arrays. Before this, I used to manually code everything in HTML. My question is, can you create an array based on the values of another array? var pmmain =["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", ...

Is there a way to locate a specific document in MongoDB by its ID without conducting a search

Seeking guidance on efficiently retrieving a document from mongodb by its ID. Need to ensure fast performance by directly targeting the specific document with the given ID. As a beginner, any detailed insights or solutions would be greatly appreciated. ...

Conceal flexbox item depending on neighboring element dimensions or content

I've encountered an issue while using a flexbox to display two elements side by side. The left element contains text, while the right one holds a number. When the value in the right element has at least 7 digits ( > 999,999 or < -999,999), I ne ...

Obtaining the name of the image that has been uploaded using jQuery

//Image upload function $(function() { $(":file").change(function() { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = imageIsLoaded; reader.readAsDataURL(this.files[0]); } }); }); function im ...

Begin composing in Excel

I am looking to manipulate an existing Excel file by writing values from an array and closing it all on the client side. Here is the code snippet I have been using: for (var c=0; c<arrMCN.length; c++) { var mcnCreate = arrMCN[c]; var mcnNumber =mcnCre ...

IE browser transparency effect on canvas

I have encountered an issue when drawing a shape on canvas using kineticJS and setting the fill to none. The code snippet I am using is below: var rect = new Kinetic.Path({ x: 0, y: 0, data: 'm 2.0012417,2.0057235 ...

Problem with jQueryUI Sortable cancel property preventing input editing

Currently, I am utilizing jquery-3.2.1.min.js and jquery-ui.min.js version 1.12.1 The task at hand is to create a sortable list where certain elements are not sortable (specifically, other sortable lists). It is crucial that the input elements remain edit ...

importing a text file into the appropriate input field on an HTML form

I've been experimenting with this JavaScript code and I can't seem to get it to work as intended. The code is designed to save the value of a single textbox into a text file that can later be loaded back into the same textbox. However, I'm f ...

Create a music player application using the React context API

Here is a code snippet for implementing a music player using context: import React from 'react'; import { BarSongTitle, BottomBar, Button, PlayList, Song, SongTitle, } from './styles.js'; import { songList } from './con ...

The error message "TypeError: res.json is not a function in express.router" indicates that

I encountered the following error message and I'm not sure how to resolve it: TypeError: res.json is not a function I have reviewed the express documentation but couldn't find any syntax errors or issues. Here is my code: index.js import expr ...

AngularJS postback method fails to trigger

Seeking assistance with my angularJS AJAX postback method. Below is the HTML code I have created: <html xmlns="http://www.w3.org/1999/xhtml" ng-app> <head runat="server"> <title></title> <script src="Scripts/angular.js ...

Opening a modal from a different component in Angular 6

I am attempting to launch a modal that is associated with a separate component. However, I encountered an error ERROR TypeError: Cannot read property 'show' of undefined Here is my code: product-catalog.component.html <app-cart-table-modal& ...

Struggling with populating a dropdown in MVC with JSON data fetched from an API using jQuery/JavaScript

I am struggling to bind the JSON data retrieved from an API to a dropdown list. I am having trouble extracting the values for id and name from the JSON format shown below: { "categories": [ { "categories": { "id": 1, ...

Dragging and dropping elements using Jquery to various positions on the screen

I am working on a project with draggable buttons and a droppable textarea. When I drag a button onto the textarea, it displays some code. If I drag another button, the text related to that button is added to the existing code. My query is how can I insert ...

Experiencing problems with various React Carousel libraries when it comes to displaying

I have been attempting to integrate Carousel libraries into my react app, but I am encountering a common issue with all of them. The Carousels show the items on the first slide, but subsequent slides do not display any items, even though they exist within ...

`Launch link in new browser window`

Seeking assistance with a coding issue. I'm attempting to have links open in a new tab, but I haven't been successful using the href attribute. Below is the code snippet from src/utils/menu.js: const menu = [ { name: 'App& ...

Maintaining the Syntax when Copying HTML to a Text Area

In my project, I rely on markdown for text editing. The markdown is converted to HTML and then stored in the database for display in the view. When users want to edit a post, the stored text is retrieved from the database and used as the initial value in ...

Accessing an object from an AngularJS controller in an external function

I previously inquired about this issue and received a suggestion to add a service, but it did not solve the problem. I am trying to access a variable from a controller ($scope) within an external function. Below is a snippet of the example: app.controll ...

Creating the x and y coordinates for drawImage in HTML5

Understanding the x and y axis has posed a challenge for me: //retrieve last known x and y coordinates ...code var p = $("#draggable"); var offset = p.offset(); var x = offset.left; var y = offset.top; //establish new font siz ...