Updating an array in MongoDB with $addToSet logic

I'm facing an issue while trying to populate the "signedUp" array in my Timetable Schema on MongoDB. Despite successfully updating other fields of the schema, the signedUp array always remains empty. I have verified that the variable being added is not empty.

Below is my Schema:

var TimetableSchema = new mongoose.Schema({

date: {
    type: String,
    required: true,
    trim: true
  },
  spaces: {
    type: Number,        
    required: true
  },
  classes: [ClassSchema],
  signedUp: [{
    type: String
  }]

});

Despite multiple attempts, I couldn't add any value to the signedUp array. Here's the excerpt from my API update request:

id = {_id: req.params.id};
space = {spaces: newRemainingCapacity};
signedUp = {$addToSet:{signedUp: currentUser}};
Timetable.update(id, space, signedUp, function(err, timetable){
    if(err) throw err;
    console.log("updates");
    res.send({timetable});
});

Thank you.

Answer №1

To find more information on db.collection.update(), you can refer to the official documentation. The second parameter in this function is used for the update operation, while the third parameter represents any operation options that are required when using $addToSet as the third parameter. Your update operation should be structured like the example below:

id = {_id: req.params.id};
space = { $set: { spaces: newRemainingCapacity }};
signedUp = { $addToSet:{ signedUp: currentUser}};
update = { ...space, ...signedUp }

Timetable.update(id, update, function(err, timetable){
    if(err) throw err;
    console.log("updates");
    res.send({timetable});
});

Answer №2

In this code snippet, the variables space and signedUp are being used together as the second argument.
You can give it a try with the following code:

id = {_id: req.params.id};
space = {spaces: newRemainingCapacity};
signedUp = {$addToSet:{signedUp: currentUser}};
Timetable.update(id, {...space, ...signedUp}, function(err, timetable){
    if(err) throw err;
    console.log("updates");
    res.send({timetable});
});

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

Click on any checkbox to select all checkboxes at once

I have created a table with each column containing a checkbox. My goal is to select all checkboxes in the table when I click on the checkbox in the top row (th). Can someone guide me on how to achieve this? Below is my code: <table style="width:100%"& ...

How can I place an icon on a specific location in a Highcharts map?

I am currently utilizing Highcharts to showcase maps within my application. I am aiming to achieve two specific functionalities: 1) Upon clicking on any area, I want that area to be highlighted in red {completed} 2) Upon clicking on any area, I intend f ...

Finding it difficult to differentiate shapes based on the number of sides

Seeking to identify the type of shape based on the number of sides passed in. The code provided only recognizes the first index, which is a triangle. I suspect this is because I am not correctly comparing the number of sides to the sides property in the ...

Is the 'match()' method available in node.js? If it is, what is the proper syntax to use it?

I attempted to utilize the .match() method in node.js, but encountered an error stating that has no method 'match'. Here is the section of code where I invoke the method: fs.readFile('proxy.txt', function (err, data) { if (data.mat ...

Problem with jQuery datetimepicker plugin not being identified as a date by Date() object wrapper

I have a component that allows users to select a date and time using the datetimepicker plugin found at this link. Here is my current configuration: $('#startDate').datetimepicker({ format: 'Y-m-d\\TH:i:s', }); When I c ...

An Unexpected Appearance of Special Characters in a Python dictionary created from AWS and transmitted to JavaScript via a Django view

In my quest to gather information about my infrastructure, I am working on constructing a dictionary that can be converted into JSON objects. These objects will then be passed to JavaScript for display purposes. I have experimented with using both json.du ...

Steps for adding a sound effect, such as a button click noise, when clicking on a div tag

I'm currently working on an app using the Ionic Framework and I need a quick and easy method to play a sound when a div is clicked. Here's what I have so far: <div ng-click="sound()"></div> $scope.sound = function () { //play so ...

Looking to include a cookie in the API header of a web browser opened through Python selenium?

I'm currently working with Python Selenium and I've encountered a problem that I need help with. I am executing a JavaScript script in an open web browser. result = driver.execute_script(''' return await fetch("https:/ ...

Exploring collision detection in Three.js

I'm fairly new to 3D and Threejs. I've created a scene with a ground, where many cubes are positioned on top of it. http://jsfiddle.net/whurp02s/1/ My goal is to select the cubes that intersect with the yellow rectangle. To achieve this, I re ...

Ideas for utilizing jQuery to extract data from CSS files

Hey there, I'm facing an issue on my HTML page where I have jQuery included. In my CSS file, I have quite a lot of lines and I'm trying to figure out how to read all styles for a specific element from the external CSS file rather than the inline ...

Managing data within nested structures in mongodb

Is there a way to update the values within the discussionReplay object, specifically the trio, comment, commentImg, and commentOwner? Currently, the User.findOne method returns the user, and my goal is to identify the correct discussion based on the matchi ...

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...

Utilize a Loader with excessively rapid request

Can anyone offer advice on how to handle requests that are too fast to display a loader properly? I currently have a submit button that displays a loader until Firebase responds (ajax request). However, the response time from Firebase is extremely quick ( ...

Is it possible to omit certain columns when extracting data from a Kendo grid?

My challenge involves extracting data from a Kendo grid using the following JavaScript call: var data = JSON.stringify($(".k-grid").data("kendoGrid").dataSource.data()) This retrieves all properties in the C# class for the records. There are three proper ...

Having trouble getting jquery to filter json data based on the selected option

I have developed a code using jQuery to filter the options in a drop-down list based on the selection made. The data is in JSON format and is fetched from a database. However, when I select an option from the drop-down list, the code does not enter the loo ...

Tips for retrieving error messages using the Scala/Java MongoDB api

I'm currently using Casbah, a Scala library for MongoDB. I am encountering an issue with one of my insert operations. val builder = MongoDBObject.newBuilder builder += "_id" -> token.uuid builder += "email" -> token.email builder += "creationTi ...

What is the reason for the compatibility issue between Vue-lang and filters?

I have implemented vue-lang from https://github.com/kvdmolen/vue-lang, but I am facing some issues. PROBLEM There is an example in the JSON file: "messages": "You have {0} {1} messages" Following this example, I added a filter to my code: <p>{{$ ...

Parent Directory Injector: Prioritizing Injection of Parent Directories

Currently, I am utilizing 'grunt-injector' to inject a list of files using 'app/**/*.js'. However, I am facing dependency errors due to the alphabetical order in which the files are injected. To avoid these issues, I am looking for a so ...

List/Table with collapsible sections for easier navigation

Looking to develop a unique single select scrollable table/list with collapsible groups using JavaScript, HTML, and AngularJS. Check out the design inspiration here: https://i.sstatic.net/Xv3uA.png As a bonus challenge, implement drag and drop functionali ...

Solving Issues with Image Rotation and Positioning

I am encountering difficulties when trying to reposition an image that has been previously rotated using the transform rotate property. Specifically, after rotating the image, the top and left attributes do not update accordingly, resulting in the image a ...