tom
tom

Reputation: 718

Meteor upsert equivalent

How soon will the upsert command be implemented in Meteor?

And, what is the best way to do the same thing in the mean time?

Something like this is what I'm doing at the moment:

if typeof ( item = Items.findOne({title:'Foo'}) ) == 'undefined'
    item = Items.insert({title:'Foo'})
else
    Items.update(item._id, {$set: {title:'Foo'}})
# do something with item

Upvotes: 5

Views: 3642

Answers (3)

user3413723
user3413723

Reputation: 12273

Upsert is really easy with this trick. you just check if it has an _id property:

if(item._id){
  //update
}else{
  //insert
}

Upvotes: 0

alanning
alanning

Reputation: 5217

How soon will the upsert command be implemented in Meteor?

UPDATE: @Thomas4019 points out that upsert is now supported:

v0.6.6

"Add upsert support. Collection.update now supports the {upsert: true} option. Additionally, add a Collection.upsert method which returns the newly inserted object id if applicable."

Source: History.md

Usage documentation: http://docs.meteor.com/#upsert

-- original answer follows --

There is a card on the Trello Meteor Roadmap which you can vote on to indicate its importance to you: https://trello.com/c/C91INHmj

It is currently in the "Later" list which means it will be a while before it is implemented unless it receives a lot of votes.

The other important thing to note is that since meteor is open-source, you could implement the necessary changes yourself and submit back.


What is the best way to do the same thing in the mean time?

There are several solutions but which is most appropriate for your use-case is impossible to tell without more knowledge of your design.

  1. Use the code as is, add an unique index to the collection, and handle the duplicate key error if/when it arises

  2. Change design to implement explicit optimistic concurrency.

The core of both of these solutions is the same, gracefully handle the error case. #1 is easier to implement. #2 allows for greater flexibility in how the optimistic concurrency is handled.

Upvotes: 5

lastid
lastid

Reputation: 469

If you really want to do that, you can use the mongodb connection directly: MongoInternals.defaultRemoteCollectionDriver().mongo.db.collection('myCollection').update(query, update, {upsert: true}). Of course this connection is not documented so there is a chance that it can be changed in the future.

Upvotes: 0

Related Questions