How to update an object in an array within a collection using ExpressJS and MongoDB

I'm having trouble updating an array within a collection. I can't seem to find the object in the array and add new values to it. I've tried a few methods, but it looks like I can't use collection methods on arrays?

router.post('/mountain_rescue_update', function(req, res) {
  var collection = db.collection('rescuemodels');
  var id = req.body.id;

  collection.update({"type": "FeatureCollection"},function (err, doc) {
     if (doc) {
         doc.find({"features": []}, function (err, result) {
             if (err) throw err;

             res.send(result);
         });
     }
   });
    }); 

In the FeatureCollection, there is an array called features. I want to perform a find operation on that array, locate the object by its id, and then push new data if possible.

How do I find an array so that operations like find and update can be performed? I know that the expression features: [] seems incorrect, but I don't know how to locate it.

I tried something like this

collection.find({"features":{"properties":{"date":id}}}, function(err,doc){
     console.log(doc);
  }

If a collection contains a document with an array of features, shouldn't this query work?

In MongoDB, I found

       db.rescuemodels.find({"features.properties":{"title":"Wild Wolfs"}})

This should search within the collection features and return all objects where properties.title is Wild Wolfs?

Here is my JSON:

{
  "_id" : ObjectId("54f50753a879d4e045b24878"),
  "features" : [
     {
         "properties" : {
             "title" : "Alona 45D",
             "description" : "...",
             "date" : ISODate("2015-03-03T01:00:40.842Z"),
             "urgency" : "Low",
             "phone" : "675 675 345",
             "completion" : "NO",
             "rescuer" : "Aleksander Gagarin"
             },
         "geometry" : {
             "coordinates" : [
                 11.2637333,
                 23.1135565
                 ],
             "type" : "Point"
           },
        "type" : "Feature"
        },...etc

      ],
  "type" : "FeatureCollection",
    "__v" : 0
   }

I managed to locate the object in the document's array. Now, I just need to update some properties.

 db.rescuemodels.find({"type":"FeatureCollection"},{"features": {$elemMatch:{"properties.title":"W"}}})

If anyone knows how to fix this statement, please let me know

   db.rescuemodels.update({"type":"FeatureCollection"},{"features":{$elemMatch:{"properties.title":"W"}}},{$set:{"features":{"properties":{"title":"XXX"}}}})

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

Utilize the native HTML attribute to capture the mouse wheel event

I'm interested in utilizing the mousewheel event in my project, but all the information I've found online relies on addEventListener(). I want to detect it using native HTML and CSS. In simpler terms, I'm hoping for something along the lines ...

Guide on creating an HTML5 rectangle for reuse using the Prototypal Pattern

I'm struggling to grasp Prototypal Inheritance through the use of the Prototypal pattern by creating a rectangle object and an instance of that rectangle. It seems like it should be straightforward, but I'm having trouble understanding why the Re ...

Position control in the Google Maps V2 interface

I am currently utilizing Google Maps API v2 with the default UI because I find the controls to be more visually appealing when set to default. <script type="text/javascript"> var map = null; function load() { map = new GMap2(document.get ...

Leap to the anchor following the article

I have implemented an Enquiry form at the bottom of my Keystone.js page, which is a modified version of the example found in the contact.js view provided by the Keystone Generator. I am able to successfully submit the form and display any errors that occ ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Tips for managing content and tables that exceed their container's boundaries

On my webpage, I have a slide-out sidebar that shifts the other contents and causes overflow with a scrollbar. I want the content to remain inside the window and adjust according to the available space. Image of Slide-out Sidebar As seen in the image, t ...

There seems to be a glitch with the functionality of the HighStocks Tooltip

I've implemented a modified version of the example from highcharts: $(function () { $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) { // Create the chart $('#co ...

Get the Label Values Based on CheckBox Status

Is there a way to retrieve the values of labels corresponding to checkboxes in HTML? I have multiple labels and checkboxes next to each other, and I want to be able to get the label values if the checkbox is checked. Can you provide guidance on how to do ...

How can you retrieve a value in NodeJS Promise (Q) even when the promise fails?

As I dive into the world of promises in my NodeJS projects, I encountered a challenging situation. Despite reading the Promises/A+ spec and conducting extensive searches online, I struggled to find an elegant solution for accessing a value generated within ...

Encountering this error for the first time - Uncaught Error displayed in the Console

I have been working on a ToDo list and it is almost complete. However, I have encountered an unfamiliar error in the console that is preventing me from creating the list. The error message reads as follows: OPTIONS http://localhost:4000/cpds/add net::E ...

Exploring the method of retrieving a wrapped object's property within a Node.js addon

Currently, I am dealing with the following JavaScript code snippet: var c = new addon.Component(); c.ComponentLength = 3 I am struggling to figure out how to structure my addon in order to execute the above code successfully. I have already gone through ...

the process of triggering animation to start automatically when a button is clicked in Web Development

I'm looking to create a React component that triggers an animation when clicked. I have a few options in mind: If the props are changed in the middle of the animation, it should restart the animation. The props can be changed by clicking a button on ...

In some web browsers, the passportjs req.isAuthenticated() method may return False due to the fact that the passport.deserializeUser

It appears that this error is quite common, with req.Authenticated() returning false. However, based on my research, it seems to affect all browsers, as previous posts have not mentioned it as a browser-specific issue. I have a web app hosted on heroku wit ...

Leveraging an Array of Objects in JavaScript

Need help with my JavaScript code! I want to adjust the date in a Date object by adding specific days and then save it. Here is what I have so far: let orderIdDateCorrectionDict = [ { "orderId": "2020053100", "dayCorrection": -146 }, { "orderId" ...

Angular - Resending unsuccessful requests

We have successfully incorporated token authorization with refresh token logic into our application. While everything is functioning as expected, we are looking to enhance the retry mechanism for requests that fail due to token expiration. The entire proce ...

Transform the image data retrieved from an external API into the appropriate format for displaying on the webpage

When I make a call to an external API, it returns image data that I want to render on my page. However, the response looks like this when I log it to the console: https://i.stack.imgur.com/GpDhH.png I'm not very familiar with image formats, so I&ap ...

Querying GraphQL: Retrieving partial string matches

I have set up a connection to a mongoDB collection using graphQL. Here is the data from the DB: { "_id" : ObjectId("59ee1be762494b1df1dfe30c"), "itemId" : 1, "item" : "texture", "__v" : 0 } { "_id" : ObjectId("59ee1bee62494b1df1dfe30d" ...

Developing a tool for switching between languages in an internationalization application

I have been exploring the implementation of Lingui(i18n) in apps. All set up, but I'm interested in adding a language switcher to enable users to change between language catalogs on my app. Here's my index.js file: import React, { useEffect } fr ...

Sending a POST request to Mailchimp via Express using React: A step-by-step guide

I'm currently working on a project where users can sign up for a new membership through a form in React and have their information added to the Mailchimp member list via my Express server. However, I've encountered a CORS error and am unsure if I ...

Start up the Express server whenever the React application is launched in a web browser

I recently created a basic react app that communicates with an express server. When running on my local machine, I can start the server with the command nodemon server.js and my react app successfully sends requests to the server (which handles email commu ...