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.