Removing a document from an array within a MongoDB collection

I have a MongoDB schema that looks like this.

{
    userID: 19202,
    products: [{ id: 020, name: 'first' }]
}

My goal is to remove items from the product array based on their id. I tried using the following command but it didn't give any errors and also didn't delete any elements from the array.

 userCart.updateOne(
                { userID: userID},
                { $pull: { products: { id: id } } }
              )
             .then((data) =>
             {
                 if(data)
                 {

 //data looks like this:
        "n": 1,
        "nModified": 0,
        "ok": 1
    }
                     return res.json({
                         status: true,
                         message: "cart updated"
                     })
                 }
             })

Answer №1

Demonstration - https://example.com/playground123

Ensure that the fields id and products.id have matching data types in your database document. In this example, they should both be numbers.

If they are both numbers,

db.collection.update({
  userID: 19202
},
{
  $pull: {
    "products": { id: 20 }
  }
})

The provided solution is not functioning properly here - https://example.com/playground456 due to the discrepancy between

"products": { id: "20" }
. The field products.id is defined as a string in the MongoDB query, whereas it is stored as a number in the database, causing a mismatch.

Answer №2

Here's a suggestion for you:

db.userCart.update(
  { userID:userID }, 
  { $pull: { items: { id: 020 } } },
  false, // Upsert
  true, // Multi
);

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

Can you please provide me with information on how I can send messages to US numbers using a toll-free number?

I attempted to utilize this code in the SNS console, but it showed a failure. I am seeking guidance on how to send a message using a TFN number. async sendMessage(testId: number) { const mobileNo = test.customer.phoneNo; const params = { Message: ...

Steps to ensure that MongoClient is accessible globally on all pages within a Node.js REST API

After researching the official MongoDB documentation, I have successfully integrated mongoDB into my NodeJS REST API using the following connection code. const { MongoClient } = require("mongodb"); // Connection URI const uri = "mongodb+s ...

I am encountering an issue where my React application is unable to establish a connection with my Express application when I dockerize them together. Can anyone

Currently tackling a project for my university that involves using a react app for frontend, an express app for backend, and mongodb as the database. Previously, I would launch the express app and react app separately before dockerizing them, and everythin ...

When installing node.js, npm does not automatically get installed as well

When I was hosting my webapp on Heroku, I encountered an error regarding bugs in my npm package. My npm package was version 3 while my node.js was version 8. Thinking that updating the npm version would solve the issue, I tried to update it but was unsuc ...

Create multiple package-lock.json files with a suffix for backup purposes

I've observed that npm generates multiple package-lock*.json files in the main directory of my project. I'm uncertain about the purpose of these files and why there are so many being created. Attached is an image displaying the generated files. ...

Using JSON Zip Response with Node.js

Hi there! I'm relatively new to working with node.js and I'm currently attempting to send a zip file containing JSON results, but I've been encountering some unexpected difficulties along the way. My tech stack includes NodeJS, ExpressJS, L ...

Problem with Angular2, NodeJS, and Passport Integration

At the moment, my Angular2 front-end is running on localhost:3000 while the NodeJS back-end (using KrakenJS) is running on localhost:8000. When I input the credentials and make a call to the this.http.post('http://localhost:8000/login', body, { h ...

Are there alternative approaches to launching processes aside from the functions found in child_process?

Having trouble with NodeJS child_process in my specific use case. Are there other methods available to start processes from a node.js application? So far, Google has only been pointing me towards child_process for all of my inquiries. Edit I am looking to ...

Configuring API paths based on environment variables with Express and Angular deployed on Heroku

I have a specific task I need help with, and I'll provide more details below. In my main Angular JavaScript file, I need to define a string that determines the server path for my app depending on whether it's in a production or staging environme ...

Backend is currently unable to process the request

Whenever a user clicks on a note in my notes page, a request is supposed to be made to the backend to check if the user is the owner of that particular note. However, for some reason, the request is not being processed at all. The frontend is built using ...

Node.js connection is limited to the localhost environment

Recently, I developed a compact Node.js application utilizing connect that not only serves up a webpage but also sends periodic updates while recording user observations to a disk file. Although it works flawlessly on localhost, I encountered difficulty e ...

Error code 400 encountered when processing Stripe webhooks

I've been working on integrating stripe webhooks into my node.js/express application, but I keep running into a 400 response from the stripe cli. Even though I followed the documentation closely and ensured that the secret key for the webhook is corre ...

Guide on utilizing a dual-parameter route in Node.js with the GET method

Need help with using 2 parameters in 1 route (get)? Check out my code below: router.get('/', function (request, response) { Result.find(function(error, results){ if (error) console.log(error) response.render('index&a ...

Node.js MySQL REST API query fails to execute

I am developing a login/sign up API using nodejs, express, and mysql. Despite receiving the "Successful Sign Up!" message without any errors during testing, the user table in the database remains empty. Below is the query I am attempting to execute: con. ...

Is it possible to configure npm install to install "bin" executables directly into the local node_modules directory (rather than the .bin directory)?

In my Node project, I am able to package it into a tarball using npm pack, and then install it in another directory for testing purposes. This allows the files specified in the "bin" section of my package.json file to be symlinked correctly into the node_m ...

What are some solutions for resolving the common issue of encountering a "Failed to parse JSON" error in npm?

Encountering a recurring issue with npm when executing the npm start command in a react project folder after a period of inactivity. Error logs displaying 'Failed to parse json' and 'package.json must be actual JSON, not just Javascript&apo ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...

Integrating social login using vue-authenticate with passport in a Node.js environment

I've been working on integrating Facebook login with vue-authenticate and passport. Successfully logged into my Facebook account, I obtained the 'Callback code' as well. Here is my callback URL: http://localhost:8080/auth/callback?code=AQD0 ...

The 'Alias[]' type does not share any properties with the 'Alias' type

I encountered an issue: The error message 'Type 'Alias[]' has no properties in common with type 'Alias'' appeared. Here is my Alias setup: alias: Alias = { id: 0, domain_id: 0, source: '', dest ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...