This is how a document structure could be in my case:
{
"_id" : "P9H59RuSbnm45erj7",
"description" : [
{
"content" : "Something",
"language" : "en",
"timestamp" : 1476958705
},
{
"content" : "Irgendetwas",
"language" : "de",
"timestamp" : 1476958705
}
]
}
Now I want to update the content of a specific language. But the description array could have missing languages.
{
"_id" : "P9H59RuSbnm45erj7",
"description" : [
{
"content" : "Something",
"language" : "en",
"timestamp" : 1476958705
}
]
}
So what I am doing is to check first if the language is existing, then
- If it is existing, I will do a simple update / $set
- If it is not existing, I will do a update / $addToSet
My question is, if this can be simplified. Do I really have to check for the existing language and then use two different update-queries? With this the code gets pumped up...
I'm using this code in my meteor app, so I'm using minimongo.
if (Collection.find({ _id: 'P9H59RuSbnm45erj7', 'description.language': 'en' }).count() > 0) {
Collection.update(
{
_id : 'P9H59RuSbnm45erj7',
'description.language': 'en'
},
{
$set: {
'description.$.content' : value,
'description.$.timestamp': Math.floor(Date.now() / 1000)
}
}
);
}
else {
Collection.update(
{ _id: 'P9H59RuSbnm45erj7' },
{
$addToSet: {
description: {
content : value,
language : 'en',
timestamp: Math.floor(Date.now() / 1000)
}
}
}
);
}