user1496093
user1496093

Reputation: 189

Meteor upsert with mongo

I need to use upsert because something a record in my Accounts schema (see below) may not exist. The defining factors for its existence are adviserID and period. If a record that matches both of those exists it should just update the record.

However when I run this, I get this error: Sanitized and reported to the client as: Adviser id must be an object [400]. When I console.log(adviser) inside the updateOrder method it does indeed report correctly the adviser ObjectID.

Any help would be appreciated. Thank you.

Upsert method:

Meteor.methods({
  updateOrder: function(adviser, order, period) {
    Account.upsert(
    {
      adviserId: adviser,
      period: period
    }, {
      $set: {
        adviserId: adviser,
        order: order,
        outstanding: order,
        period: period
      }
   });
  }
});

Schema:

Schema.Account = new SimpleSchema({
  "adviserId": {
    type: Object,
  },
  period: {
    type: Date,
    label: "Order Period"
  },
  order: {
    type: Number,
    min: 0,
    label: "Order Number"
  },
  outstanding: {
    type: Number,
    min: 0,
    defaultValue: 0,
    label: "Outstanding Number"
  }
});

Upvotes: 0

Views: 1084

Answers (4)

user1496093
user1496093

Reputation: 189

Thank you Bryukhanov Valentin. Converting to type String resolved my issues.

Thanks also to those that replied.

Upvotes: 0

Valentin Briukhanov
Valentin Briukhanov

Reputation: 1283

From SimpleSchema Docs:

If you have a key with type Object, the properties of the object will be validated as well, so you must define all allowed properties in the schema.

adviser in your method should be a string because you use it for the find (in upsert). If your adviser is a string, then just fix your schema for {type: String, regEx: SimpleSchema.RegEx.Id}. Or if you want to use an object, then you need describe it or add blackbox option.

Upvotes: 1

Pankaj Jatav
Pankaj Jatav

Reputation: 2184

This is how we upsert in meteor.

 Shares.update({
                 adviserId: adviser,
                 period: period
              }, {
                 $set: {
                    adviserId: adviser,
                    order: order,
                    outstanding: order,
                    period: period
                 }
              }, {
                  upsert: true
              })

Upvotes: 1

Stephen Woods
Stephen Woods

Reputation: 4049

More than likely you want adviserId to be a string. MongoDB internal ID objects are strings in Meteor.

Upvotes: 1

Related Questions