user3848987
user3848987

Reputation: 1657

Insert/update subelements or insert complete document in collection - depending on existing main-element

If I send data from a form, I first check if a document with the title already exist in the collection. If this isn't the case, the data should be inserted. Else only a part of the data will be inserted - if it doesn't exist itself as I want to avoid duplicates.

So this is how I do it:

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]
    });
}

But there are two problems for me:

  1. Is there a smarter way to do that? Right now I have to do first a find().count() before inserting/updating.
  2. My code doesn't work as I get the error Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]

Update

Would this be the same?

Collection.update(
    { journal: journal }, 
    { 
        $addToSet:  { article: article },
        $set:       { journal: journal, article: article }
    },
    { upsert: true }
);  

Upvotes: 0

Views: 26

Answers (1)

user3142695
user3142695

Reputation: 17352

Just create a method on the server like this

Meteor.methods({
    'saveToCollection': function(collection, journal, article){
        if (global[collection].find({journal: journal}).count()) {
            global[collection].update(
                { journal: journal }, 
                { 
                    $addToSet: { article: article }
                }
            );          
        }
        else {
            global[collection].insert({ 
                journal: journal, 
                article: [article]
            });
        }
        return true;
    }
});

Upvotes: 1

Related Questions