What is the best way to modify an object within an array that is nested inside another object using mongoose?

I need to update the "numberOfUpVotes" field for the idea with the title "Een centrale plek voor alle ideeen" in my database. How should I go about doing this?

My current code isn't throwing any errors, but it's also not updating the value as expected. Here's what I've attempted so far:

 Board.findOneAndUpdate(
        {"ideas.numberOfUpVotes": 23},
        {$set: {"numberOfUpVotes": 2}}, // $set
        {new: true},
        function (err, doc) {
            if (err) return res.send(500, {error: err});
            console.log("hallo");
        });

Here is a snippet of my data:

{
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
    {
    _id: ida1,
    userId: id1,
    title: 'Een centrale plek voor alle ideeen',
    text: 'A central hub where all ideas are displayed on a screen or something similar. Users can vote on these ideas using their phones',
    date: new Date('2019-04-12'),
    numberOfUpVotes: 23,
    },
    {
    _id: ida2,
    userId: id1,
    title: 'Een uber voor kerstbomen',
    text: 'Does something like this already exist?',
    date: new Date('2019-04-11'),
    numberOfUpVotes: 1,
    }
],
QRcode: 'This is a QR code'
}

Answer №1

It is possible to achieve this functionality without relying on mongoose, using a method similar to the following.

const board = {
  collectionName: "Board",
  boardName: "IdeaBoard Schiphol",
  ideas: [
      {
      _id: 'ida1 (demo)',
      userId: 'id1 (demo)',
      title: 'A central place for all ideas',
      text: 'Shortened for demonstration',
      date: new Date('2019-04-12'),
      numberOfUpVotes: 23,
      },
      {
      _id: 'ida2 (demo)',
      userId: 'id1 (demo)',
      title: 'An Uber for Christmas trees',
      text: 'Does something like this already exist?',
      date: new Date('2019-04-11'),
      numberOfUpVotes: 1,
      }
  ],
  QRcode: 'This is a QR code'
};

// Find the filtered record and update its value
// The found record is a reference, so the value 
// is indeed changed within the object
board.ideas.filter(idea => idea.numberOfUpVotes === 23).shift().numberOfUpVotes = 2;

// Quod Erat Demonstrandum
console.log(JSON.stringify(board, null, " "));

Answer №2

After careful consideration, here is my definitive response:

UpdateBoard(
    {"thoughts._id": mongoose.Types.ObjectId("def456")},
    {$inc:{"thoughts.$.totalLikes": 1}},
    function (error, data) {
        if (error) return res.send(500, {message: error});
        console.log("Operation successful! :)");
    })

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

Upon inserting Node 5, an error with the code EINVALIDTYPE occurred in npm

Recently, after I upgraded to Node 5, I've been encountering an error in the terminal every time I try running anything with npm. npm -v: 2.14.12 Desperately attempting to update npm to the latest version: MacBook-Pro-de-MarceloRS:promo-auto-loan ...

Prevent redirection on buttons within ionic lists

THE ISSUE: I am facing an issue in my Ionic app where I am using the ion-list component. Each item in the list can be swiped to reveal a button (add/remove to favorites). Additionally, each item serves as a link to another page. The problem arises when ...

What is the best way to showcase images in an Angular application when the images are saved in the server uploads folder of a Node.js

In my node.js server, I have a separate directory where I store files in the uploads folder and save image paths in the db. The directory structure looks like this: node_modules src uploads |category-name-folder |image-name.jpg |category-name-folde ...

Is it necessary for React to pass onClick as props to sub components?

Attempting to activate an onClick function within a sub-component by including the onClick in the parent component did not yield the desired outcome. // parent component class MainForm extends Component { // code here handleClick = () => { con ...

What is the process for adding information to datatables using jQuery?

I have been struggling to make a data table in jQuery function correctly. I am able to append data to the table, but the sorting, pagination, and search features are not working. Even though the data is visible in the table, it shows as 0 records. I am wor ...

Encountering difficulty in adding content to a table using JavaScript. An error message appears stating that assignment to a function

I am utilizing ajax to retrieve an item from a web API, and then attempting to allocate attributes of that item to a table: function find() { var id = $('#contentID').val(); $.getJSON(uri + '/' + id) .done( ...

Node.JS has deceived us with its false promises of `import` support

Could it be that I am making a mistake? I have been eagerly awaiting the experimental ES6 module loader in Node.JS since version 10. This feature is crucial for me to seamlessly use the same code in both the browser and node environments. This is how I w ...

What is the minimum number of characters required to embed JavaScript using the HTML5 <script> element?

Is this the most efficient way to include external JavaScript on a page, now that the type attribute of the <script> tag can be omitted in HTML5? <script src="URL"></script> Is there a way to optimize this further, especially if a frame ...

Utilize the active tabpanel MUI component with Next.js router integration

Trying to implement active tab functionality using router pid This is how it's done: function dashboard({ tabId }) { const classes = useStyles(); const [value, setValue] = React.useState(""); useEffect(() => { con ...

Ways to determine the numerical value of a specific word chosen by a user

I'm struggling to retrieve the position number of a word selected by a user. For instance If I have a simple paragraph with two words: Hi and Bob <p>Hi Bob</p> Therefore, logically Hi=1 and Bob=2. Now, if the user selects Bob, I want t ...

What is the best way to create a static site using Express and EJS?

Having used the Express Application Generator and selected "EJS" from the default options, I have a functional site where the server is only required to update the cached API once a day. In my previous projects with hexo.js, all EJS templates were rendere ...

Is there a way for us to determine the time at which the user last took a screenshot or photo?

I am currently developing a website using Django and I have a unique requirement. I need to access the last image that a user has taken on their phone, without the image being shared by anyone else. The photo must be captured by the user's device itse ...

Incorporating Functions from an External Script in ReactJS/GatsbyJS

One of the functionalities on my website involves dynamically inserting a script into the head when a form element is focused, enabling it to load faster. This process is achieved using basic vanilla JS rather than React Helmet, as shown below: const handl ...

What are your thoughts on this method? Verifying the existence of a variable or setting it to

const pictureEntity = updateUserDto?.picture ? await this.filesService.find(updateUserDto.picture) : null; if (pictureEntity) { const url = await this.filesService.getFileUrl(pictureEntity); } Is the method used to assign the value to pictureEn ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

Chosen option within the AntD Select component

Using the AntD select component, there seems to be an issue where it displays "id" instead of "name" when selecting options. Is there a solution available for this problem? const MyComponent = () => { const data = [ { id: "5c83c2d ...

Ensuring that touch events are activated on Firefox's desktop browser

Testing on a Windows 7 desktop with touch capabilities, I performed a simple test that looked something like this: temp_div.addEventListener('touchstart', function(e){ /*confirm */ }, false) temp_div.addEventListener('pointerdown', fun ...

What steps can I take to troubleshoot this issue involving Django and AJAX?

Looking to pass the selected ID of an option via an AJAX request to Django 2.1, but encountering errors. As a newcomer to Django and web development, I would appreciate any help in resolving this issue. document.addEventListener('DOMContentLoaded&apos ...

Regular Expression: Identify specific characters at the start or end of a string

I am in need of a regular expression (regex) that can precisely match the char set 'AB' only if it is at the beginning or end of a string, and then replace it with an empty string. It is important to note that the regex should not match parts of ...

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...