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

Eliminate the ArrayOfObjects by filtering out the items with a specific ID

Here is an array of objects I've named mycart[]: [{"id":"6","quantity":"20","price":1500,"title":"casual blue strip"}, {"id":"10","quantity":"2","price":1500,"title":"casual blue round neck"},{"id":"5","quantity":20,"price":150,"title":"casual ...

Choosing the subsequent element that comes before

<tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> <tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> &l ...

Having trouble converting the file to binary format in order to send it to the wit.ai api through node.js

I am having trouble converting an Audio file to Binary format for sending it to the Wit.AI API. The node.js platform is being used for this purpose. On the front-end, user voice is recorded using the Mic-recorder Module. Any guidance or suggestions would b ...

Is it possible to obtain the X-Y coordinates of the ray collision location in relation to the targeted face?

I have been working on determining the ray collision coordinate in relation to the targeted face... The following is my code snippet: var fMouseX = (iX / oCanvas.width) * 2 - 1; var fMouseY = -(iY / oCanvas.height) * 2 + 1; //Utilizing OrthographicCamer ...

Separate a tab delimited text file and store it into an array using JavaScript

Looking to parse a text file with tab-separated values in JavaScript and add them to an array? Here's how you can achieve this while excluding the header: Id Symbol 1 A 2 B 3 C 4 D 5 E 6 F 7 G This is what I have attempted so far: va ...

Minimize redundancy in the process of adding functions to a function queue

Currently, I am delving into JavaScript animations and utilizing multiple functions to add components to the animation queue. The structure of these functions is quite repetitive as shown below: function foo(arg1, arg2) { _eventQueue.push(function() { ...

Facing some unexpected issues with integrating Django and AngularJS, unclear on the cause

In my simple Angular application, I encountered an issue. When I run the HTML file on its own in the browser, the variable name "nothing" is displayed as expected. However, once I integrate the app into Django by creating a dummy view that simply calls a t ...

Is there a way to animate without specifying a duration?

Exploring the capabilities of the Animated component in react-native, I came across the powerful Animated.timing(); function which operates within a specific duration defined as duration: 2000,. While duration is useful in certain scenarios, I found myself ...

Re-sequence a contiguous array by mapping and filtering its elements

Within my React code, I have a list component that utilizes array.map to display a list of items. The list items have alternating backgrounds; every other item's background color is determined by whether the id field from the data structure is even o ...

The rotation of Google Maps always returns to its default position when I open the map information window by clicking on it

I have successfully implemented a Google Map with tilt and heading functionality, allowing the map to rotate horizontally. However, I am facing an issue where clicking on a marker resets the map back to its original position. You can view the map by follo ...

JavaScript's static function and variable that operate asynchronously

Encountering an issue with a "static" function in JavaScript (Node.js server). User.create = function(data, _callback){ var node = db.createNode(data); var _user = new User(node); _user.save(function(err){ if(err) return callba ...

NodeJs running Mongoose encounters bottleneck while attempting to save an excessive number of documents due to Out of Memory

I am currently working on a script that identifies documents within a MongoDB database that are missing a DateUTC value. The script then loops through these documents and sets the date using a datestring value found within each document. Since the data i ...

Utilizing Jquery's .GET method to retrieve and handle JSON data

In the jQuery snippet below, I am trying to fetch product data from . However, I am facing difficulty in iterating through the loop to access all 30 products along with their details. $.get("https://dummyjson.com/products/1") .done(function ...

Switching from jQuery to vanilla JavaScript, iterating through each HTML tag in a loop

Here is my current jQuery code that I am looking to convert into vanilla JavaScript. var elements = []; document.querySelectorAll('*:not(script, style, iframe)').forEach(function(element) { elements.push(element); }); I have tried using d ...

Using JavaScript Functions to Resize Buttons and Change function on Click

I have a button in my code that triggers CSS changes by adding and removing classes. The JavaScript for this function works as intended - clicking once adds the class, clicking again removes it, and so on. However, I also implemented a feature to remove t ...

Go to the identical page with a message embedded in it

Creating a login page using JSP involves an index.jsp file which contains the form and javascript scriplets. The connectivity to an Oracle database and validation of username and password are handled in check1.jsp. The problem arises after entering the us ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

retain the input data from the form by using the keyup event

Currently, I have a scenario where an input field is used to capture user input. Instead of displaying the entered value directly, I am looking to store it in a variable and subsequently use it to retrieve data from a database. Below is the code snippet I ...

Access and retrieve real-time JavaScript variables directly from a website

Question: I am curious about the possibility of accessing JavaScript variables on a website from C#. Since the scripts are on the client side, is it possible to read their values live through C#? Any assistance or guidance on this matter would be greatly ...

PHP and JQuery not working together to update database

Essentially, I am trying to update the status based on the unique id. Despite no errors being thrown, the status remains unchanged. index.php $(document).ready(function() { $('.seatCharts-seat').click(function(){ var id = jQuery(th ...