I’ve searched the forums and the mongodb docs but I’m still struggling with this one. I have an Article model, with a property called triangle_key which is an array of objects:
const articleSchema = new mongoose.Schema({
triangle_key: [{
token: Number,
unique_beer: String,
unique_cup: String,
}],
})
Users can submit an array of triangle_keys via a form. This array gets sent to the server on req.body.key and looks like this:
[
{token: "1", unique_beer: "blue", unique_cup: "B"},
{token: "2", unique_beer: "yellow", unique_cup: "A"},
...
]
What is the best way to update every triangle_key in the Article with its corresponding value in req.body.key? In other words, if a user submits four triangle_keys with tokens 1, 2, 3 and 4, I would like to update the triangle_keys with token 1, 2, 3 and 4 in the Article to match. If the user submits a triangle_key with a token that doesn’t currently exist in Article.triangle_key, then I want to add it to Article.triangle_key.
I currently solve this by looping through the array in req.body.key and querying the Article every iteration… The below code works, but is very slow.
// add or update each token/unique_beer pair to the article key
for (const inputSet of req.body.key) {
const updateResults = await Article.updateOne(
{ _id: req.params.article_id },
{ $set:
{
"triangle_key.$[elem].token": inputSet.token,
"triangle_key.$[elem].unique_beer": inputSet.unique_beer,
"triangle_key.$[elem].unique_cup": inputSet.unique_cup,
}
},
{
arrayFilters: [ { "elem.token": { $eq: inputSet.token } } ]
}
);
// if it couldn't update it (didn't find a match), then push a new one.
if (updateResults.modifiedCount === 0) {
await Article.updateOne(
{ _id: req.params.article_id },
{ $push:
{
triangle_key:
{
token: inputSet.token,
unique_beer: inputSet.unique_beer,
unique_cup: inputSet.unique_cup,
}
}
}
)
}
}
Is there a faster/better way to do this?