How to leverage the $push operator in Angular-Meteor to seamlessly update MongoDB

I'm attempting to transfer arrays from one collection to another, and this is the code snippet I've implemented in my server.js file:

    updateSettings: function(generalValue) {
     let userId = Meteor.userId();
       let settingsDetails = GeneralSettings.findOne({
   "_id": generalValue
 });
            Meteor.users.update({
     _id: userId
   }, {
     $push: {

       "settings._id": generalValue,
       "settings.name": settingsDetails.name,
       "settings.description": settingsDetails.description,
       "settings.tag": settingsDetails.tag,
        "settings.type": settingsDetails.type,
       "settings.status": settingsDetails.status
     }


   })

}

The meteor method used is updateSettings. The first collection is GeneralSettings while the second collection is user. The objective is to push arrays from GeneralSettings into the users collection. However, the current result obtained looks like this:

 "settings" : {
    "_id" : [ 
        "GdfaHPoT5FXW78aw5", 
        "GdfaHPoT5FXW78awi"

    ],
    "name" : [ 
        "URL", 
        "TEXT" 

    ],
    "description" : [ 
        "https://docs.mongodb.org/manual/reference/method/db.collection.update/", 
        "this is a random text" 

    ],
    "tag" : [ 
        "This is a demo of an Url selected", 
        "demo for random text"
    ],
    "type" : [ 
        "url", 
        "text"
    ],
    "status" : [ 
        false, 
        false
    ]
}

The desired output should be:

 "settings" : {
    "_id" : "GdfaHPoT5FXW78aw5",

    "name" :  "URL", 

    "description" :  
        "https://docs.mongodb.org/manual/reference/method/db.collection.update/", 

    "tag" :"This is a demo of an Url selected", 

    "type" :  "url",


    "status" :    false 



},

To achieve the desired output above, what modifications should be made in my server.js code?

Answer №1

In this particular scenario, it is advised against using "dot notation". The $push operator requires an Object and will add the content on the right side to the array specified by the key on the left:

// Simplify your task by updating this object directly
settingDetails._id = generalValue;

// Then you are simply adding the entire object to the "settings" array
Meteor.users.update(
  { _id: userId }, 
  { "$push": { "settings": settingDetails } }
)

If you were to use "dot notation" for each item, it would create arrays for each individual key provided. It should be one array key with the object as the argument.

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

Transforming text into visual content using a live preview div powered by jQuery

Looking for a way to display images in real-time as a user types letters into a textarea field. When a user inputs a letter like 'k', an image associated with that letter should appear. Currently, only pre-entered letters on the page show images, ...

What is the method for running code once the $digest cycle has finished?

I have created a sortable list in my Angular Controller that gets populated with data. This list includes an extra element with controls that can also be dragged. My goal is to ensure that the extra element remains in place after the $digest cycle runs, s ...

Tips for deciding between various options for a single resource in angularjs

I have a client application that needs to access a resource's rest parameter through three different paths: resource/:resourceId/restparameter, restparameter/:restparameterId/restparameter, and restmethod/:restmethodId/restparamter. I attempted to ach ...

Having trouble attaching to ng-repeat

After creating a basic ASP.NET WEBApi that retrieves a list of customers, I am attempting to connect it with the UI. Here is my WEB Api Controller code: public class DummyController : ApiController { public HttpResponseMessage Get() ...

"Complete with Style: Expand Your Horizons with Material-UI

The Autocomplete feature in Material UI is not expanding to the full width of the TextField element. Any suggestions on how to fix this issue? https://i.sstatic.net/3ccdp.png https://i.sstatic.net/KdkrO.png ...

The issue of underscorejs being undefined arises when trying to load it using both XMLHttpRequest and

I am attempting to dynamically load underscorejs using XMLHttpRequest and eval function function includeScriptSync(scriptUrl) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", scriptUrl, false); xmlhttp.onreadystatechange = function() ...

Execute a Jquery function following an automatic focus

Is it feasible to activate a function after an autofocus event? I attempted it, but when my textarea receives autofocus, I have to click away and then click on the textarea again to trigger the function. Here is my code: $('#test').focus(); $(& ...

Display geographic data using d3 with geoJSON

I am struggling to render a geoJSON file using d3 because I am having trouble targeting the correct features for projection. Instead of working with the typical us.json file used in many d3 examples, my current map focuses on United States "Commuting Zone ...

What is the best way to ascertain the variance between two Immutable.js Maps?

I currently have two unchangeable maps: const initial_map = Map({x: 10, y: 20)} const updated_map = Map({x: 15, y: 20)} Can anyone advise on how to find the changes between the two maps? The expected outcome should be: Map({x: 15}) ...

Exploring 2D Arrays in ECMAScript 6

In my quest to avoid using traditional for loops, I am searching for a method to generate and populate 2D arrays using ES6. The goal is to have an array filled with all 0s. While I've attempted various strategies, the following code demonstrates one a ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

Disabling ESLint rule in a React application while using WebStorm

Currently, I am working on a React application in WebStorm using the standard setup for React. I have not configured any specific linting rules before, so all error and warning messages that are popping up are due to some default settings. Whenever I execu ...

The absence of IdMemberMap occurs when employing the "Representation Serialization Options."

Utilizing MongoDB, I aim to maintain a clean model by adopting the following approach: This is how my class looks like: public class Person { public string Name { get; set; } public string Id { get; set; } public Person() ...

Steps for aligning an image and text within an icon next to each other

I'm looking to align a small PNG image next to some text within an icon. How can I achieve this? Currently, they are stacked vertically. Here is the current layout - I want the two elements side by side instead. The structure of the division is unique ...

Combining two arrays based on a common id

Here are two arrays: var members = [{docId: "1234", userId: 222}, {docId: "1235", userId: 333}]; var memberInfo = [{id: 222, name: "test1"}, {id: 333, name: "test2"}]; I want to merge them into a single array by matching user ids programmatically. The c ...

Creating dynamic forms and tables on an HTML webpage

I'm struggling to dynamically add table elements and form elements in an HTML page. My goal is to automatically add input boxes with labels when a user enters a number in the input box without having to click any button. I believe using the 'keyu ...

Enhance the performance of your React/NextJS app by controlling the rendering of a component and focusing on updating

I'm facing an issue with my NextJS application that showcases a list of audio tracks using an <AudioTrackEntry> component. This component receives props like the Track Title and a Link to the audio file from an external data source. Within the ...

Implementing a click event on a selection option – tips and tricks

When I want to select an option, I can use the following script: Javascript $("#practice-area optgroup option").click(function(){ // insert your function here }); HTML <select name="practice-area" id="practice-area"> <option value="0">S ...

How can I extract mandatory fields from a Document using mongoengine?

How can I extract a list of required fields from the document I've created? Here is an example document: nickName = StringField(required=True) password = StringField(required=True) firstName = StringField() lastName = Strin ...

Finding and removing an element using Jquery

$.ajax({ type: "GET", url: "ajax/getLinks.php?url=" + thisArticleUrl }).done(function (data) { var extractedContent = $(data).find("#content > div > div.entry.clearfix"); extractedContent.find("#content > di ...