Updating nested data in MongoDB without creating duplicate objects

My goal is to add new data into an existing document:

Graph.update(
    { id: id }, 
    {
        $push: {
            tooltips: {
                element: Session.get('tooltipID'),
                text: text
            }
        }
    }
);

Everything is going smoothly, however, I am encountering an issue where if there is already existing data in tooltips, instead of adding a new object, I need it to update the existing one. This is because each element (tooltipID) should have a unique object.

I want to prevent duplicate entries for the same element-value in tooltips.

{
    "_id" : "c4bKur6TKcgFHGLZZ",
    "data" : "[]",
    "tooltips" : [
        {
            "element" : "2d4edaaf",
            "text" : "Lorem"
        },
        {
            "element" : "2d4edaaf",
            "text" : "ipsum"
        }
    ]
}

However, it should be allowed to have multiple objects in tooltips as long as the element is unique...

I attempted to include upsert:true in the update() function, but unfortunately, it did not work as intended.

Answer №1

It is certain that utilizing upsert will not function with an embedded document.

One possible solution could be

Graph.update({id:id}, 
    {
       $addToSet: {
           'tooltips': {
              element: Session.get('tooltipID'),
              text: text
            }
       }
})

This method guarantees there are no duplicates in tooltips;

alternatively, you may employ $set

Graph.update({
  id:id,
 'tooltips.element': Session.get('tooltipID')
  }, 
  {
 $set: {
    'tooltips.$.text':text
   }
})

or you can remove before adding

Graph.update({
    "id":id
}, {
    $pull: {
        'tooltips': {
            "element": Session.get('tooltipID')
        }
    }
})
    Graph.update(
    { id: id }, 
    {
        $push: {
            tooltips: {
                element: Session.get('tooltipID'),
                text: text
            }
        }
    }
);

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

Typemoq and Angular-cli are incompatible with each other

Many Angular 2 cli applications come with karma-jasmine tests already set up. If you decide to enhance your tests by using typemoq, simply run the command npm install typemoq --save-dev Then, include typemoq in one of your test files like this: ...

Preventing the dispatch function from being overwritten by an empty state

Scenario: I am currently exploring the concept of React/Redux and aiming to understand the data flow. The process involves axios dispatching actions -> reducers setting state to props -> Component rendering. As a newcomer to the Frontend world, ...

Calculate the Pythagorean Theorem with HTML and JavaScript

I'm currently attempting to create a Pythagorean theorem calculator using HTML and Javascript. The goal is for the calculator to determine any side when given two side values. I've implemented if statements in my code, but for some reason, it doe ...

React hooks for managing a to-do list

Hey there, I am a Javascript (ReactJS) beginner and I have created a simple to-do list app using react hooks. Currently, when a user writes something new, it replaces the old text. I need some advice on how to keep everything the user has written intact wi ...

Looking for a categorized list of unique special characters and their classifications

I am currently developing a web application focused on providing machine translation support. This involves taking source text for translation and converting it into the user's desired language. At the moment, the application is in the unit testing p ...

Viewing multiple pages and maintaining sessions in Laravel

I am currently working on a quiz application that involves multiple pages depending on the user's selection. However, I have encountered an issue with Laravel's pagination not saving previous page inputs. Is there a way to resolve this problem? A ...

Converting a tree structure into JSON with the help of tree-model-js

Would it be possible to find a method to convert a TreeModel into a JSON string for storage purposes and then use tree.parse() to reconstruct it later on? Whenever trying JSON.stringify(root), an error is thrown due to cyclic references caused by children ...

The JQuery condition is failing to accurately recognize the span checkbox

I am facing an issue with checking the status of a span checkbox to see if it is checked or not. For some reason, I believe that the detection of the checkbox's status is not working correctly. Below is a simplified version of my current code: ...

How to use JavaScript and regex to control the state of a disabled submit button

I have a challenge where I need to activate or deactivate a submission button in a form called btn-vote using JavaScript. The button will only be activated if one of the 10 radio buttons is selected. Additionally, if the person-10 radio button is chosen, t ...

DxDataGrid: Implementing a comprehensive validation system for multiple edit fields

I'm currently working with a DxDataGrid within an Angular Application. Within this particular application, I have the need to input four dates. I've implemented validation rules that work well for each individual field. However, my challenge aris ...

When Vue is clicked, it appears to trigger multiple methods simultaneously

Currently, I am learning Vue and encountered a problem that I need help with. When using the v-on:click directive to call a method, all other instance methods are also called when the same method is used elsewhere. HTML: <div id="exercise"> &l ...

The hyperlink refuses to open in a new tab

The jQuery BlockUI plugin is causing me some confusion. My goal is to include a clickable link within the content locked by the plugin, but no matter what I try - including adding target="_blank" - it just won't direct to the specified URL. Any sugg ...

Having trouble accessing the height of a div within an Iframe

Here is the issue I am facing: I need my iFrame to adjust its size based on a div within it, but every attempt to retrieve the size of this div results in 0. var childiFrame = document.getElementById("myDiv"); console.log(childiFra ...

What is the process of creating {{shortcodes}} in a node.js, express.js, and jade.js application

After utilizing #{user.name} in my input, it is returning a string with "#{user.name}". My goal is to extract data from the database by including some {{shortcode}}, as illustrated in the image below. The format of the shortcode can vary and does not neces ...

What is the best way to populate MongoDB with information retrieved from an external API?

Recently, I've been diving into the world of NodeJS with mongoose & mLab. As someone new to these technologies, I'm slowly piecing together my model. Here's what it looks like for now, with plans to expand the schema down the road. cons ...

How can Mongodb regular expressions be used to search for a substring that ends with '..' or has a '.' in the middle of a field in mongo?

I'm looking to scan through several thousand documents in Mongo to identify records where a specific field contains certain substrings: Any text followed by 2 dots. For instance: Co.. Any text containing a '.' in the middle of the string ( ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Creating a user-friendly form in a Nuxt/Vue application that enables dynamic attribute creation

I am currently working on designing a form that enables users to create different variations for a product within a Nuxt/Vue application. The goal is to provide users with the ability to specify attributes for each variation using a text field. These attr ...

Parsley.js now supports the use of the attribute `data-parsley-errors

Currently, I am attempting to integrate the errors container (e.g., data-parsley-errors-container="#ErrorSummary") with parsley.js. Most aspects are functioning properly, but I've encountered an issue. Specifically, I am looking to solely adjust the ...

Converting JSON data into an array of objects for managing React state using hooks

My React hook component is designed to interact with an API, fetching a JSON response. Here's the code snippet: import React, {useEffect, useState} from 'react'; import axios from 'axios'; const fetch = () => axios({ " ...