Tips for updating a single field in MongoDB with Mongoose

This is my code snippet:

import mongoose from 'mongoose';

const UserData = new mongoose.Schema({
    additionalData: Array,
    name: String,
});
mongoose.model('UserData', UserDataSchema);
mongoose.set('useFindAndModify', false);

export default mongoose.model('UserData');

I'm looking for a way to update the additionalData property of the UserData model so that another array can be appended.

For example, let's say the additional array is

[ 1, 2, 3]

Answer №1

To incorporate new elements into your MongoDB documents, consider using the $addToSet operator.

await UserData.update({name:"something"},{ $addToSet: { additionalData: [1,2,3] })

Alternatively,

await UserData.updateOne({name:"something"},{ $addToSet: { additionalData: [1,2,3] })

If you want to apply this operation to all documents unconditionally:

await UserData.update({},{ $addToSet: { additionalData: [1,2,3] })

To remove multiple values from an array, utilize the $pull operator.

await UserData.update({},{ $pull: { additionalData: { $in: [ 1, 2,3 ] }}})

If you only need to eliminate a single value:

await UserData.update({},{ $pull: { additionalData:1 }})

Answer №2

If this doesn't align with your intended query, please leave a comment so I can make the necessary adjustments to the response.

const updatedArray = [ 4, 5, 6];
const targetName = 'bar';
mongoose.model('UserData').updateMany({
    name: targetName
}, {$set: {
    extraData: updatedArray
}});

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 best way to convert a string array KEY to numbers based on the length of the array in PHP

In my PHP code, I have an array structured like this: Array ( [Cpu] => Cpu [Memory] => Memory [Ping] => Ping [Interface - Ethernet] => Interface - Ethernet [Disk - C:] => Disk - C: [Disk Reponse - C] => Disk Repons ...

Launch a modal window that displays a form generated using ngx-formly, which is nested within another form also created with

I have been utilizing ngx-formly to generate Angular forms dynamically from JSON data, and it has been working smoothly. One interesting scenario I encountered involves a custom button on a form that needs to open a modal dialog containing another form upo ...

Node.js express is having trouble parsing the body after moving routes to their own folder

After organizing my routes into their own folder, I am facing an issue with parsing the response body. The controller is sending the body correctly. Previously, when the routes were in the server.js file, the app worked without any issues. Server.js BEFOR ...

How can I log or dump data when working with JavaScript using AngularJS, Karma, and Jasmine?

Usually, when I want to record data in JavaScript, I opt for logging it to the console with console.log("What I had for dinner yesterday"); However, while exploring a Karma/Jasmine unit testing video tutorial for AngularJS hosted by Vojta Jína, I came ac ...

Exploring the Component API in VueJS 3 with Typescript: Learn how to assign a class to a template ref

Is there a recommended way to add/remove CSS classes from a template ref using the Vue 3 Composition API and typescript? When trying to use modal.value, I encountered the following typescript errors: const modal = ref(null) results in Object is possibly ...

Create additional rows both preceding and following the specified row from the JSONB column

I am reaching out for assistance as I am struggling to solve this particular issue. I currently have a correct result based on real physical data in a table. SELECT row_number() OVER (ORDER BY PR."Priority") AS "LOS", "SpeedLessTha ...

Creating a function to wrap the return type of an AJAX call within the success method

My Web Service consistently returns one object from a class I defined on the server side. When using the $.ajax function's success method, I always receive this object. On the client side, I am looking to add some functions for quickly displaying its ...

The data returned by the Axios response.data object is full of nonsensical information when making a

I tried experimenting with Axios by writing a quick test function, but the response.data object I received was all jumbled up. I've been searching online for a solution, but I haven't been able to find one. It seems like all the Axios tutorials o ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

Combining an unlimited amount of elements in an array using JavaScript

Currently, I am facing a challenge while trying to develop an application using Javascript. What I aim to achieve is a webpage that collects input values from a textbox and stores them in an array. Subsequently, I need to create a function that can add t ...

Does the callback in setTimeout get executed right away?

How can I achieve a fade-in effect for an element that remains on the page for 7 seconds before fading out, with the ability to cancel it at any time? I have implemented the following functions. However, when I invoke info_timeout.setup(ele, 'some msg ...

What is the best way to trigger a jQuery UI dialog using an AJAX request?

My website includes a jQuery UI Dialog that opens a new window when I click the "create new user" button. Is there a way to open this window using an AJAX request? It would be useful if I could open the dialog-form from another page, such as dialog.html ...

My component's state is not updating properly when using this.setState (the state value is numerical)

I am struggling with the code snippet: this.setState({score: counter}); It seems like the state is not updating as expected. Even when I try this.setState({score: 5}) or score:"a string", it still does not work. Am I overlooking something here? Regardless ...

Comparison of the output of ps au | grep ssh in Node.js (using spawn/pipe) versus the shell revealed discrepancies

I have been experimenting with node streams and child processes. My goal is to emulate the following shell command using pipes: ps au | grep ssh Here is the code I came up with: var spawn = require('child_process').spawn; var ps = spawn(&ap ...

Question about finding elements in a PHP array

I'm dealing with arrays, some of which are multidimensional. I am looking for a solution to check if all the values in these arrays are NULL. What is the most efficient and effective method to determine if ALL values in an array (including values with ...

Issue with implementing setTimeout on await fetch() result

I'm trying to figure out how to add a setTimeout to my request response when using await fetch. Currently, each response is being sent to a DIV in the HTML, but I want to introduce a delay of 5 seconds before each response appears. I attempted this s ...

The Backstretch jQuery plugin seems to be malfunctioning

My goal is to achieve a full-screen background image using the Backstretch jQuery plugin on my homepage. Here's the code I've implemented: <div class="startslide"> <script> $.backstretch('IMG_3628.jpg'); </script> < ...

Is there a way to manually add route resolve data to a controller without using automatic injection?

Two routes in my application share a controller, but one route requires data to be resolved before the view loads while the other does not. Here is an example of the routing segments: ... when('/users', { controller: 'UsersCtrl', ...

Fixing JSON conversion and UTF-8 string encoding issue in Ruby on Rails 3.1

Issues arose when exporting a UTF8 string using to_json. The concern stems from the fact that in the following scenario: ruby-1.9.2-p290 :005 > "anche il più remoto".encoding => #<Encoding:UTF-8> ruby-1.9.2-p290 :006 > {:text => "anc ...

After clicking multiple times within the modal, the modal popup begins to shift towards the left side

I successfully implemented a modal popup in my project, but encountered an issue where the popup moves to the left side if clicked multiple times. Despite searching extensively online, I have not been able to find a solution to this problem. Below is the ...