How to use Upsert

Could someone post a link to a tutorial or blog posting somewhere, with a detailed example of how to use [collection].upsert?

Thanks!

Are you asking when it’s appropriate to use it? As for how to use it, it’s pretty simple: http://docs.meteor.com/#/full/upsert

It’s used pretty much the same as update but will insert if no matching document is found and the callback will return the _id of the added document.

Ah, I should have started reading on update then. My first need was an upsert, so it never dawned on me to go to update. And I just now realized the dashed stuff to the right of “select” and “modifier” were actually links. I thought that was just some special markup for specific types.

OK, I still don’t get it.

I want to insert the following fields:

owner: Meteor.userId(),
firstName: firstName,
lastName: lastName,
address: address,
city: city,
state: state,
country: country,
addDate: new Date()

Unless the owner already has a record, in which I case I want to update these fields:

address: address,
city: city,
state: state,
country: country

so the selection is well documented … I can just do:

{ owner: Meteor.userId() },

but the modifier for this isn’t obvious. My best guess is:

{
    firstName: firstName,
    lastName: lastName,
    address: address,
    city: city,
    state: state,
    country: country,
    addDate: new Date()
}

But I don’t want it to update addDate, firstName, lastName.

1 Like

You’ll need to use the $setOnInsert operator.

3 Likes

Ahhh, now it’s making sense. :slight_smile: