Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Meteor Upsert

Tags:

mongodb

meteor

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.

like image 265
Varun Jain Avatar asked Oct 24 '13 01:10

Varun Jain


People also ask

How does the Upsert option work?

Or in other words, upsert is a combination of update and insert (update + insert = upsert). If the value of this option is set to true and the document or documents found that match the specified query, then the update operation will update the matched document or documents.

Does MongoDB have Upsert?

Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter. In that case, the applied update operation will update the documents. If the value is true and no documents match the condition, this option inserts a new document into the collection.

Is there an Upsert option in the MongoDB insert command?

Since upsert is defined as operation that "creates a new document when no document matches the query criteria" there is no place for upserts in insert command.

What is Meteor collection?

Collections are Meteor's way of storing persistent data. The special thing about collections in Meteor is that they can be accessed from both the server and the client, making it easy to write view logic without having to write a lot of server code.


1 Answers

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     } }); 
like image 135
Varun Jain Avatar answered Nov 08 '22 19:11

Varun Jain