I’ve looked at similar questions but couldn’t find my answer. I’ve got this info:
{
"_id": "631337640754675725",
"characters": [
{
"name": "Druuwu",
"scores": [
{
"date": "2023-09-03",
"score": 100
},
{
"date": "2023-09-03",
"score": 1000
},
{
"date": "2023-09-03",
"score": 101
},
{
"date": "2023-09-03",
"score": 102
}
]
},
]
}
And I’m updating/adding using this logic here:
await culvertSchema.findOneAndUpdate(
{
_id: interaction.user.id,
"characters.name": selectedCharacter,
},
{
$addToSet: {
"characters.$[index].scores": { score: culvertScore, date: reset },
},
},
{
arrayFilters: [{ "index.name": selectedCharacter }],
new: true,
}
);
How could I make it so that if a score with the same ‘date’ already exists, it would just update it with a new score? Instead of creating a new record with the same date and different score. Thanks!
2
Answers
Here’s the modified code to achieve this:
This way, you’ll get the behavior where it updates an existing record with the same date and creates a new record, if the date does not exist in the "scores" array.
Consider refactoring your schema to
characters
level like this if possible. Most of the complexity of your case comes from handling doubly nested array.Mongo Playground