Get or craft in Meteor

How can I make a function get_or_create

in Meteor (something like https://docs.djangoproject.com/en/1.8/ref/models/querysets/#get-or-create )?

Do I need to use

var element = Elements.findOne({number: 32});
if (element) {
  var elementId = element._id;
} else {
  // override element
  element = Elements.insert({number: 32});
  var elementId = element._id;
}

// do something with elementId

      

It seems not very convenient.

I wondered if Meteor or MongoDB has something already built in like Collection.upsert()

.

+3


source to share


1 answer


Checkout MongoDB findAndModify

. Below is an example of what you are describing.



collection.findAndModify({
  query: { _id: "someId" },
  update: {
    $setOnInsert: { foo: "bar" }
  },
  new: true,   // return new doc if one is upserted
  upsert: true // insert document if it does not exist
})

      

+2


source







All Articles