What is the best method for modifying a property within an array of objects in MongoDB?

I am trying to alter the state of a property ("active") within an array of objects by setting it to either false or true based on which function I should invoke.

{
    "_id": ObjectId("59fc98974aceec3e70a18715"),
    "name": "Mostaganem",
    "destinations": [
        {
            "active": true,
            "seaport": ObjectId("59fc98594aceec3e70a18712")
        },
        {
            "active": false,
            "seaport": ObjectId("59fc98884aceec3e70a18714")
        }
    ]
}

Although it works when executed in robo3T, the state change does not take effect when called through the API. Can you provide assistance?

async deactivate(id) {
    /* await this.update(
        { destinations: { $elemMatch: { seaport: id } } }, 
        { $set: { 'destinations.$.active': false } }, 
        { multi: true }); */
    await this.update({ '_id': id }, { $set: { 'destinations.$[].active':    false } });
}


async deactivate(id) {
    // await this.update({ destinations: { $elemMatch: { seaport: id } // }, {    $set: { 'destinations.$.active': false } }, { multi: true });
    await this.update({ '_id': id }, { $set: { 'destinations.$[].active': false } });
},

Answer №1

Here is the solution to my own scenario:

{
"_id" : ObjectId("539b6b5dc7ac9bc0316e3d61")
"permissions" : {
        "projects" : [
            {
                "edit" : true,
                "view" : true,
                "projectId" : ObjectId("532708cba8ed009019151b13"),
            }
        ],
}

If you want to update the view permission in the projects of this user:

db.users.update({ _id: ObjectId("539b6b5dc7ac9bc0316e3d61"), 'permissions.projects.projectId': ObjectId("532708cba8ed009019151b13") }, { $set: {'permissions.initiatives.$.view': false }})

The dollar($) sign refers to the object within the projects array that matches the specified id, allowing you to update that specific object.

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

Traversing a JavaScript object and saving variables into a string

I am facing an issue with storing values within a JavaScript object notation based on the field selected by the user. While I can store the value in a string separated by commas, when the element I'm trying to access is an array, I receive [object obj ...

Sails.js encounters issues initializing Passport.js when SSL is implemented

Currently utilizing Sails.js (v0.9.4) and passport(local strategy) with no issues. The need arises to configure Sails.js behind SSL. Therefore, the setup includes: (Port 8080 selected for SSL). Upon starting Sails, it responds correctly, except for those ...

if statement for a method within the ng-click directive

Whenever I click the button, I want to either execute createRole() if RoleName is not set or EditRole() method if RoleName is set. However, for some reason, EditRole() is being executed for both cases. <button type="submit" ng-click="selectedItem.Rol ...

Iterate through intricate array structures using the most efficient approach and minimal complexity

I have a scenario where I need to call an API that returns data in the following format: [{ Id: string, Value: string, Value2: [{Id: string, Value3: string}] , { Id: string, Value: string, Value2 ...

Transfer information to an ExpressJS server in order to display a fresh view

I'm struggling to figure out how to transfer data from the client side to an ExpressJS server in order to generate a view based on that information. When users choose different parameters on the client side, they update the 'data-preference&apos ...

Remove the active class from a list item using History.js

My goal is to add the active class to a link when clicked in my AJAX app, triggering statechange on History.js. I'm struggling with saving the current active link(s) with the state so that the active class is appropriately added or removed when naviga ...

The justify-between utility in Tailwind is malfunctioning

Can someone help me figure out how to add justify-between between the hello and the user image & name? They are in different divs, but I've tried multiple ways without success. I'm fairly new to this, so any advice would be appreciated. This ...

MongoDB's $elemMatch operator is exhibiting unexpected behavior

I have a specific collection that looks like this: >db.prueba.find({}) { "_id" : "A", "requi" : null } { "_id" : "D", "requi" : [ "A", "B" ] } { "_id" : "E", "requi" : [ "B" ] } { "_id" : "B", "requi" : null } { "_id" : "C", "requi" : [ "A" ] } My goa ...

Is it possible to streamline the chaining of promises generated from MongoDB queries?

This feature allows for the display of all collections in a MongoDB database, along with the count of documents in each collection using bluebird promises. function displayMongoCollections(db) { var promises = [] db.listCollections().toArray().the ...

A guide on extracting split values and assigning them to individual variables

Currently, I'm working on a project utilizing node.js, express, mongo, and socket.io. After successfully retrieving geolocation coordinates and storing them in a hidden input field, I encountered an issue when attempting to save the data into the data ...

Inject data into an Angular 2 template

Does anybody know of a method to pass variables to templates in Angular2? Suppose I have the following code snippet: <div *ngFor="foo in foos"> <ng-container *ngTemplateOutlet="inner"</ng-container> </div> --------------- <n ...

Having trouble deciphering the undefined jquery scroll at the top

I have been attempting to resolve this error without success, so I am turning to you with my specific issue. I am using a jQuery scroll feature that navigates to the hashtags in the menu. When it reaches the targeted hashtags, the menu item color should ch ...

Why isn't the findOne method of the mongoose recognizing the variables I'm using?

Recently delving into the world of node.js, express, and mongoose. Here is a snippet of my code. It's worth mentioning that I've hardcoded "P4" in the findOne method and it works perfectly fine. However, I'm encountering issues with recogn ...

Unable to modify the date format within the datepicker widget

Currently, I am facing an issue with a datepicker on my website. The datepicker disables dates that are stored in the database, which is functioning properly. However, there is a problem with the input format as it is set to mm-dd-yy while the date format ...

Is there a way to efficiently retrieve the total number of customers on a specific date using Mongoose (MongoDB) in just one query?

I am relatively new to working with Mongoose (NoSQL) and I am curious about how to calculate the number of users based on the date of their last update (updated). At the moment, I am able to retrieve the total number of customers, but I am unsure about ho ...

Tips for closing a (Javascript iframe) on an ASP.NET platform

I am trying to close an iframe using a button click, but my current code is not working as expected: <td> <a href="utility.htm" toptions="group = links, shaded = 1, type = iframe, effect = fade, width = 900, height = 900, layout = quicklook"> ...

How can I efficiently remove elements from the end of an array in Vue.js?

Is there a way to splice data starting from the back with a higher index? When clicking on the .delete div, how can I make it so the .image-box div deletes starting from the end? I need help implementing this feature in my code. Here is a snippet: < ...

Establish a connection to AWS by utilizing MQTT.js

Looking to create a web page that connects to an AWS server? While python-Paho-mqtt allows for the use of tls_set to add security certificates and more, how can we achieve the same with MQTT.js? And if unable to do so, what are the steps to run python-PAHO ...

What is the best way to add user login information to the request pipeline in Express.js?

In my current project, I've been working on a middleware that is responsible for extracting the user model and attaching it to the request pipeline. Although I have successfully implemented a token extractor middleware that attaches the token to the r ...

Issue with submitting content using Asp.Net Core along with Vue.JS and Axios

Hello there! I'm a novice when it comes to Vue.JS and I'm facing an issue while trying to post an object using axios, as all the properties are being received as null values. Let me share my basic Model: public class Employees { public int ...