Varun Jain
Varun Jain

Reputation: 903

How to use Meteor Upsert

Having a bit of trouble getting my Meteor upsert function working. I am fairly (200 lines of code) new, and I'm having a bit of trouble.

The collection keeps on having additional rows inserted, rather than just updating. I spend the past 30 minutes googling, but I can't find any examples I can understand.

Here's my code:

Values.upsert(
    {
      // Selector
      source: "SourceOne",
      currency: "USD"
    },
    {
      // Modifier
      value: res.data['data']['last']['value'],
      time: Date.now(),
    }
  );

I've also tried

if(Values.find(
      {},{fields: {'source':"SourceOne", 'currency': "USD"}}
    )) {
    Values.update(
      {
        source: "SourceOne", 
        currency: "USD"
      },
      {
        value: res.data['data']['last']['value'],
        time: Date.now()
      }
    );
  } else {
    console.log('blah');
    Values.insert({
      source: "SourceOne", 
      currency: "USD",
      value: res.data['data']['last']['value'],
      time: Date.now()
    });
  }

And still can't seem to figure it out.

Upvotes: 36

Views: 18260

Answers (4)

YourBestBet
YourBestBet

Reputation: 1749

Mongo.Collection#upsert(selector, modifier, [options], [callback])

ARGUMENTS

selector: Mongo Selector, Object ID, or String Specifies which documents to modify

modifier: Mongo Modifier Specifies how to modify the documents

callback: Function Optional. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.

OPTIONS: multi Boolean True to modify all matching documents; false to only modify one of the matching documents (the default).

https://docs.meteor.com/api/collections.html#Mongo-Collection-upsert

Upvotes: 0

Aishwarya Sharma
Aishwarya Sharma

Reputation: 21

Try this:

values.update({"id":id},
       { $set: {
          value: res.data['data']['last']['value'],
          time: Date.now() // no need coma here
      } },
      { upsert: true }
    );

Upvotes: 2

Varun Jain
Varun Jain

Reputation: 903

Figured it out through trial and error:

Values.upsert({
    // Selector
    source: "SourceOne",
    currency: "USD"
}, {
    // Modifier
    $set: {
        value: res.data['data']['last']['value'],
        time: Date.now() // no comma needed here
    }
});

Upvotes: 53

provolot
provolot

Reputation: 139

The above doesn't work for IDs. This works for me (with the same syntax as update):

Values.upsert(id,
{
  // Modifier
  $set: {
      value: res.data['data']['last']['value'],
      time: Date.now() // no need coma here
  }
}
);

Upvotes: 13

Related Questions