In the event that data is sent from a form, the first step is to verify if a document with the same title already exists in the collection. If it does not, then the data should be inserted. Otherwise, only a portion of the data will be inserted to prevent duplication.
This is the method I follow:
var journal = list[0].value,
article = {
author: list[1].value,
pageNumbers: list[2].value,
reference: id
}
if (Collection.find({journal: journal}).count()) {
Collection.update(
{ journal: journal },
{ $addToSet: {
article: article
}
});
}
else {
Collection.insert({
journal: journal,
article: [article]
});
}
However, I encounter two issues:
- Is there a more efficient way to accomplish this? Currently, I need to first perform a find().count() before inserting or updating.
- My code does not work, resulting in the error
Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]
Update
Would this alternative method be equivalent?
Collection.update(
{ journal: journal },
{
$addToSet: { article: article },
$set: { journal: journal, article: article }
},
{ upsert: true }
);