Removing a SubDocument from an Array in Mongoose

For my project, I am utilizing mongoose to create a database. The schema for my Class looks like this:

const mongoose = require('mongoose')

const classSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  consultant: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Consultant',
    required: true
  },
  startYear: {
    type: String,
    required: true
  },
  classname: {
    type: String,
    required: true,
    unique: true
  },
  studentList: [
    {
      code: {
        type: String,
        required: true
      },
      fullname: {
        type: String,
        required: true
      }
    }
  ]
})

const Class = mongoose.model('Class', classSchema)

module.exports = Class

The property studentList is an array which is stored in mongoose Atlas as shown in the image below:

https://i.stack.imgur.com/Pf1WD.jpg

To delete a subdocument from the array studentList, I have created a route:

http://localhost:5000/users/:code

This is the implementation:

exports.delele_student_from_user = (req, res, next) => {
  var { code } = req.params;
  var { classname } = req.body;

  User.findOneAndDelete({
    classname,
    studentList: {
      $pull: {
        code,
      },
    },
  })
    .exec()
    .then((doc) => {
      console.log(`deleted user with code ${code} from collection User`);
      next();
    })
    .catch((err) => {
      console.log(err);
      return res.status(500).json({ err });
    });
};

However, when executing this code, I encountered the following Error:

{ MongoError: unknown operator: $pull ... 

If anyone can assist me in resolving this issue, it would be greatly appreciated. Thank you and have a wonderful day!

Answer №2

To remove a student from the user, utilize the update function.

exports.remove_student_from_user = async (req, res, next) => {
  var { code } = req.params;
  var { classname } = req.body;
  try {
    await User.update(
      { classname },
      {
        $pull: {
          studentList: { code }
        }
      }
    );
    return res.status(200).json({ message: "Student successfully removed" });
  } catch (err) {
    return res.status(500).json({ err });
  }
};

The usage of async / await has been incorporated for improved readability and efficiency.

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

Experiencing difficulties in transmitting images/files to API through reactjs and Material UI upload component

Recently, I tackled the task of creating an image upload component by utilizing an upload component from Material UI. While I have experience with this process using a simple HTML file input in the past, I found myself feeling a bit perplexed this time aro ...

Hover over a particular element using a loop in Vue.js

Is there a way to change the price button to an Add to Cart button on mouseover, considering the true false data trigger for each item? How can we specify which item to target when hovering over the price section? Below is the code snippet: template: < ...

navigating to the start of a hyperlink

I'm having issues with scrolling to anchors and encountering 3 specific problems: If I hover over two panels and click a link to one of them, nothing happens. When I'm on section D and click on section C, it scrolls to the end of section C. ...

Unsubscribing from a service method in Javascript using RxJS

After clicking a button, a function is triggered to execute. The function includes an method called "executeAction" that retrieves the current view and then passes it as a parameter to another view for future reference. async executeAction(action: ...

Is it possible to use Ajax post with localhost on Wamp server?

Looking to execute a basic POST function using Ajax on my localhost WAMP server. Here's the code I have: function fill_table() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ...

Having trouble navigating the Request and Response handling in Expressjs/Nodejs?

As I continue to delve deeper into this code, confusion seems to cloud my understanding. Here is the provided source: var express = require('express') , http = require('http') , server = express() ; var home = require('./ro ...

Extract core object from array of objects with lodash or javascript

In my code, I have an array of objects that each contain a base object with a set of values. My goal is to remove the base object from all the data and achieve the Expected result shown below. Here is an example of the array: [ { "100": { ...

"Enhancing User Experience with Multiple Conditional Checkboxes in jQuery

Having difficulty making a checkbox change some HTML content using JQuery. There is a standard html checkbox with the following attributes <input type="checkbox" name="AQN1" class="checkbox Q1" value="AQN10" id="3mcq"> <input type="checkbox" nam ...

``There seems to be an issue with JQuery.Ajax not properly displaying on Samsung Smart

I attempted to use JQuery.Ajax to interact with my webservice Below is the code snippet: Main.onLoad = function() { // Enable key event processing this.enableKeys(); widgetAPI.sendReadyEvent(); //$("#h2Test").html("Change On Text"); ...

What is the method to retrieve the exact value of {match.params.id} in React Router?

This is an example of code that I have. However, I am unsure about how to extract the value and utilize it afterwards. class CustomView extends Component { componentDidMount() { var uniqueId = {match.params.id} } render() { ...

What is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

Can an ejs template be displayed without the need to refresh the page?

I'm currently developing a game server that involves players entering a game room and getting paired with another player. One feature I would like to implement is displaying the game board without having to reload the page in order to avoid reinitiali ...

Is it possible for me to pass a value through props that is not currently stored in the state?

Within the realm of Reactjs, imagine a scenario where there exists a <Parent> component containing state and a variable named foo, which is either 'global' or local to Parent. The question arises: Can we pass foo as props using <Child v ...

The extent of utilizing the click handler in ECMA script 6

In ES6 arrow functions, the scope of this becomes available. However, there are instances where I cannot access this in an arrow function while it works with a normal anonymous function. For example: Sample 1 $(document).ready(function() { $(' ...

"Controller's $watch function fails to trigger when new items are added to an array within a directive

Within my code, I have established a two-way binding variable called publish.selected_tags that connects a directive with a controller. To monitor changes in this variable, I implemented a $watch function within my controller: $scope.$watch('publish ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Is there a way to serve server-side rendered content exclusively to search engine crawlers like Google Bot, without SSR for regular users in Next.js?

With a staggering number of users visiting the site every day, we are making strides to enhance our visibility on Google by implementing SSR (which may sound unbelievable) and achieving a richer preview when content is shared on messaging platforms. As th ...

Using React and graphql to show information on selected options across components

Currently, I'm facing a challenge in determining my next step. In productList.js, there is a straightforward select dropdown class component that displays all data from Products (id, name, brand,vintage) using graphql(apollo). It successfully sho ...

Enhancing Mongoose Functionality: Leveraging Keywords in Data Population

In my MEAN.JS application, I am utilizing Mongoose Middleware to perform searches. I am attempting to search for a specific word using the Mongoose Middleware keyword option within the fields: tags.text, description, and spot.name filters = { filters ...