Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor Allow Upsert?

Getting this error in the console when I try upserting to a collection:

"update failed: Access denied. Upserts not allowed in a restricted collection."

Here are the allow rules I've specified:

if (Meteor.isClient) {
    Meteor.subscribe('customers');
}

customers = Customers

if (Meteor.isServer) {

Meteor.publish('customers', function() {
    return customers.find();
});

customers.allow({

    insert: function (document) {
        return true;
    },
    update: function () {
        return true;
    },
    remove: function () {
        return true;
    }

    });

}

Here is the upsert part:

Customer.prototype.create = function ( name, address, phone, cell, email, website, contact, shipping ) {

var attr = {
    name : name, 
    address : address, 
    phone : phone,
    cell : cell,
    email : email,
    website : website,
    contact : contact,
    shipping : shipping
};

Customers.upsert( Customers.maybeFindOne( attr )._id, attr );

    return new Customer( attr );
};
like image 872
user3203772 Avatar asked Jan 17 '14 04:01

user3203772


2 Answers

This is a choice the development team has made.

The suggested solution is to write a method that wraps upsert. This makes the server request come from server code while the client code only runs for latency compensation. Example:

//shared code
Meteor.methods({
  customersUpsert: function( id, doc ){
     Customers.upsert( id, doc );
  }
});

//called from client
Meteor.call( 'customersUpsert', Customers.maybeFindOne( attr )._id, attr );
like image 106
user728291 Avatar answered Nov 14 '22 13:11

user728291


This is the work-around I use (using underscore's defaults function):

_upsert: function(selector, document) {
  if (this.collection.findOne(selector) != null) {
    this.collection.update(selector, {
      $set: document
    });
  } else {
    this.collection.insert(_.defaults({
      _id: selector
    }, document));
  }
}

Which assumes that selector is an object ID.

like image 21
Patrick Canfield Avatar answered Nov 14 '22 11:11

Patrick Canfield