"MongoDB query for updating a single document using $elemMatch in a

I am encountering difficulties with updating my database. The surveys collection consists of documents structured in the following format:

{
    "_id": {
        "$oid": "5aaf4f7984521736d88db4bb"
    },
    "title": "4242 ",
    "body": "4242 ",
    "subject": "4242 ",
    "recipients": [
        {
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8beacbece6eae2e7a5e8e4e6">[email protected]</a>",
            "responded": false,
            "_id": {
                "$oid": "5ab04084be3c1529bcbdcd6e"
            }
        },
        // Additional recipient objects
    ],
    "_user": {
        "$oid": "5aa5edbf8887a21af8a8db4c"
    },
    "dateSent": {
        "$date": "2018-03-20T00:11:55.943Z"
    },
    "yes": 0,
    "no": 0,
    "__v": 0
}

Using mongoose on the backend, I aim to update the database whenever a user responds to a survey.

const Survey = mongoose.model('surveys');

Survey.updateOne(
    {
        _id: surveyId,
        recipients: {
            $elemMatch: { email: email, responded: false }
        }
    }, 
    {
        $inc: { [choice]: 1 },
        $set: { 'recipients.$.responded': true }
    }
).exec();

Unfortunately, the update only succeeds when the query matches the first object in the recipients array. For example, this works:

// Successful update

However, this does not work:

// Unsuccessful update

My schema definitions are as follows:

// Schema definitions

When attempting manual queries using node, the same issue arises where only the first recipient subdocument is matched successfully.

This query finds and returns the survey:

// Successful query

But these do not:

// Unsuccessful queries

I have been researching how $elemMatch operates, and it seems that querying based on properties within the recipients array might be restricted to IDs only.

Answer №1

One issue lies in the way you are saving following emails without removing unnecessary spaces. This causes only the initial email to be correctly trimmed, while the others start with a blank space causing complications when querying for results.

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

What is the proper way to utilize --legacy-peer-deps or enforce in a vite build?

I encountered an issue with a package called react-typed in my project. To install it, I had to use --legacy-peer-deps. When deploying, I need to use vite build. However, when I run the command, I receive the following errors: 8:59:31 AM: npm ERR! node_mo ...

Navigating to a specific child component within my React application

I am currently working on a callback function in which an argument is passed from a child component (specifically CardTiles) to be processed and then sent as props to another child component. Everything is functioning correctly, but the challenge lies in m ...

Error TS2307: Module './images/logo.png' could not be located

I encountered an issue while attempting to import a local png image into my ts webpack project. The error message displayed was as follows: TS2307: Cannot find module './images/logo.png'. All other modules, such as css, svg, and ts files, impor ...

The isInvalid property fails to apply red highlighting to the input box in a react-bootstrap form

Working on creating forms using React and react-bootstrap. Currently, my form includes an email field structured like this - https://i.sstatic.net/dlbWn.png Here's the code snippet of how it looks: <Form noValidate autoComplete="off&quo ...

What is the best way to toggle between two forms with JavaScript?

I have designed a login screen with two forms inside one div. The first form contains the login box, while the second form is for registration and is hidden using CSS with display:none;. Below the login button, there is a paragraph with an anchor tag to cl ...

Serialport node failing to receive data

I currently have an RS422 serial device connected to my Windows PC using a USB to serial cable. The cable incorporates an FTDI chip and I am utilizing the corresponding VCP drivers to communicate with the device through a COM port (COM3). https://i.sstati ...

Calling another function within a loop in Vuejs causes an error

I am working with a code sample that contains data for cities including latitude and longitude values. Here is the code snippet: ... methods: { mapDrag: function () { let lat = 100; let lng = 200; this.cities.forEach(fu ...

Discover the concealed by using overflow: hidden on the parent's children

I am facing an issue with my photo gallery where I want to hide some photos initially and display how many are omitted from the gallery using overflow: hidden;. After reading through this particular response, I attempted the following solution: const a ...

Luxon DateTime TS Error: The 'DateTime' namespace cannot be used as a type in this context

I have encountered an issue while trying to set the type of a luxon 'DateTime' object in TypeScript. The error message DateTime: Cannot use namespace 'DateTime' as a type appears every time I attempt to assign DateTime as a type. Below ...

When trying to make a jQuery call using ajax, there is no response being received

I'm facing a slight issue with a gift list that is generated from SQL. My objective is to display each row as a form with a textbox and a button. When the button is clicked, I want to send the textbox value and an ID number (hidden field value) to a f ...

Discovering diversity in Angular: Learn how two distinct Class Components differ from one

Within my Parent component, I am injecting data into two @Input() Child duplicate card components to display HTML. The Parent component also has a different class that marks the distinction between the two classes. My question is, when showcasing class me ...

At what point in the pipeline will the changes made in the $set stage start to show up?

db.col.aggregate( [ $set: { X: 4, Y: "$X" } ] ) Does the field Y get set to 4 as well in this stage? ...

Is There a Way to Abandon a route and Exit in Express during a single request?

In order to ensure proper access control for the application I was developing, I structured my routing system to cascade down based on user permissions. While this approach made sense from a logical standpoint, I encountered difficulties in implementing it ...

Uploading files in NodeJS using the multer library

I am attempting to upload a file to a specific directory on the disk using the multer library. As I analyze the code, it seems that when a request is made, the file is taken from it and saved separately from the rest of the request. Is there a way to acces ...

Comparing Fluid-Framework to Signal-R: Understanding the Distinguishing Factors

Query: Recently, Microsoft unveiled the Fluid-Framework on GitHub. What are the steps to replace Signal-R with Microsoft's Fluid-Framework and what are the main differences? Scenario: It appears that Fluid supports collaboration and data synchronizat ...

Implementing a Standardized Template for Consistent Design and styling Throughout Website

As I work on building my website, I find myself struggling with some of the intricacies. The homepage is set up with a navbar and header, along with several pages that can be easily navigated to. While everything seems to be functioning properly, upon ins ...

Calculating the difference between the old scrolltop and the new scrolltop in jQuery/Javascript

I have a seemingly straightforward question, yet I am struggling to find a solution. Each time a user scrolls, the scrollTop value changes. I want to subtract the previous value from the new value of the scrollTop. However, I am unsure how to store the old ...

The FormData function is unable to retrieve the input fields of a form

My Unique Code <!DOCTYPE html> <html> <body> <div id="custom-form-sample"> <form enctype="multipart/form-data"> <input type="text" name="custom-text" /> <input type="radio" name="custom-radio" ...

Sending Functions as Props in React Using Typescript from a Parent Component to a Child Component

Trying to pass props from Parent to Child using TypeScript-React but getting an error: "Type 'void' is not assignable to type 'Function'." Parent import React from "react"; import Navbar from "./navbar"; import Main from "./main"; f ...

Difficulty activating JavaScript function - unsure of proper implementation

I'm having trouble with calling a function instead of an alert in my code. I tried using FunctionsName(); and removing the alert(''); but it doesn't seem to be working for me :( Could someone please take a look at the following code an ...