Add or update subelements, or add the entire document to the collection, based on the presence of the main element

In the event that data is sent from a form, the first step is to verify if a document with the same title already exists in the collection. If it does not, then the data should be inserted. Otherwise, only a portion of the data will be inserted to prevent duplication.

This is the method I follow:

var journal = list[0].value,
    article = {  
                author:         list[1].value, 
                pageNumbers:    list[2].value, 
                reference:      id 
            }

if (Collection.find({journal: journal}).count()) {
    Collection.update(
        { journal: journal }, 
        { $addToSet: { 
            article: article
        }
    });         
}
else {
    Collection.insert({ 
        journal: journal, 
        article: [article]
    });
}

However, I encounter two issues:

  1. Is there a more efficient way to accomplish this? Currently, I need to first perform a find().count() before inserting or updating.
  2. My code does not work, resulting in the error
    Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]

Update

Would this alternative method be equivalent?

Collection.update(
    { journal: journal }, 
    { 
        $addToSet:  { article: article },
        $set:       { journal: journal, article: article }
    },
    { upsert: true }
);  

Answer №1

To handle this scenario on the server, you can implement a method similar to the one provided below:

Meteor.methods({
    'addToDatabase': function(database, category, item){
        if (global[database].find({category: category}).count()) {
            global[database].update(
                { category: category }, 
                { 
                    $addToSet: { item: item }
                }
            );          
        }
        else {
            global[database].insert({ 
                category: category, 
                item: [item]
            });
        }
        return true;
    }
});

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

Issue with loading glb file in three.js: The 'format' property is not compatible with this material

When loading a .glb file I created in Blender using three.js, I am encountering an error message three.module.js:7950 THREE.MeshStandardMaterial: 'format' is not a property of this material.. The rest of the content loads correctly. What does thi ...

Message display showing an "[object Object]" (Node Express Passport)

Having an issue with my passport.js implementation where the flash message is not showing up when the username or password is incorrect. The logic was working fine before, but now it's broken even after copying the working version step by step. Flash ...

"Combining the power of Angularjs and the state

I've been delving into Redux, mainly in the context of using it with React. However, I use AngularJS. Is there a compelling advantage to implementing Redux instead of handling state within AngularJS scope and letting Angular manage the bindings? ...

transferring data from ejs template

In my app.js file, I have an array that stores files. To display these files on a website, I use a for-loop in ejs: <% for(let i = 0;i<posts.length; i++){ %> <li class="listtitle"> <%= posts[i].title %> </li> ...

Could you clarify that for me?

Let's take a look at the function isIsogram(str) which checks if a string is an isogram. An isogram is a word or phrase in which no letter occurs more than once. The code snippet for this function can be seen below: We are particularly interested in ...

Updating a field in Mongodb that is indexed as a 2dsphere

I understand why we cannot update primary keys that are indexed as unique. However, I am perplexed as to why I am unable to update the geolocation data which is indexed as 2dsphere. When I attempt to update geolocation data in a collection, the update do ...

Select state and city options similar to the national breakdown page

I'm attempting to replicate a state and city selection box similar to the one on the NTTS Breakdown website. You can see it in action here: When you select a state on the left side of the webpage, the city selection box displays "loading data" and th ...

Retrieving a single post from a JSON file using AngularJS

I'm currently delving into AngularJS, but I seem to be stuck on what might be a simple issue. At the moment, I have some hardcoded JSON files with a few persons in them and no actual backend set up yet. In my form, I aim to display a single person ea ...

The specified type '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' is not compatible with the expected type

I've been working on a UI layout that includes checkboxes on the left, a data table on the right, and a drop zone box. The aim is to keep the table data updated whenever a new file is dropped, and also filter the data based on checkbox selection. I ma ...

Reorganizing data with JSON using JavaScript

I have a JSON data that I am parsing with NodeJS and I need to restructure it into a different JSON format. The original JSON includes multiple "pages" objects within the "rows" object, each containing similar keys and values except for the "values" and "d ...

How can you make a dynamic 360 image that responds to mouse movements using three.js?

Is it possible to achieve a three.js effect similar to the one shown here? We have come across solutions that involve drag&drop for camera angle control, but we are interested in having the mouse position dictate where the camera points. For instance, ...

When pressed, the button changes color to a vibrant shade of blue, and not just a simple outline

I'm experiencing an issue with a button that turns blue when the user holds onto it for a while on mobile. You can see an example in the image below: https://i.sstatic.net/VmnZ8.png Adding ::selected or outline did not resolve the problem as the ent ...

What is the best way to send JavaScript data to PHP?

Is it possible to post a variable to a PHP script without refreshing the page? If so, how can this be achieved? Here is an example using jQuery: $.ajax({ url: "myphpfile.php", type: "post", data: json/array/whatever, success: function(){ ...

Storing data in a JSON format

Our team requires a service that can periodically generate up-to-date JSON data every 15 minutes for our AJAX services to consume. This JSON will be used for metric analysis and charts among other things. The reason behind the 15-minute interval is due to ...

In Bootstrap 5, clicking inside a dropdown should not cause it to open or close unexpectedly

Check out the code snippet below: <html> <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1f1212090e090f1c0d3d48534e534e">[email protected]</a>/d ...

Creating an associative array in Javascript by utilizing a for loop

I am attempting to create an array called userRow{} by using: $('#divResults tr').find('td:nth-child(2)').text(); This will fetch 12 first names from a column in an HTML table, such as John, Dave, and so on. $('#divResults tr&ap ...

Struggling to display the Three.js LightMap?

I'm having trouble getting the lightMap to show on my mesh. Here's the code I'm using: loader.load('model.ctm', function (geometry) { var lm = THREE.ImageUtils.loadTexture('lm.jpg'); var m = THREE.ImageUtils.loadT ...

Adjust the loading bar component in Material UI to allow for customizable color changes

I am currently learning how to use material ui. My goal is to customize the loading bar's CSS. I checked the documentation and utilized colorPrimary classes. However, the changes are not appearing as expected. Could you please guide me on how to resol ...

Add the content script to a webpage just one time

I am looking to inject a content script on context menu click in an extension manifest version 3. I need a way to determine if the script is already injected or not. If it hasn't been injected yet, I want to inject the content script. This condition m ...

"When attempting to render a Node inside the render() method in React, the error message 'Objects are not valid as a React child' is

On my webpage, I have managed to display the following: export class OverworldComponent extends React.Component<OverworldComponentProps, {}> { render() { return <b>Hello, world!</b> } } However, instead of showing Hello, ...