简体   繁体   中英

Get or create in Meteor

How can I make a get_or_create function in Meteor (something like https://docs.djangoproject.com/en/1.8/ref/models/querysets/#get-or-create )?

Do I have 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 so handy.

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

Checkout MongoDB findAndModify . Below is an example to achieve 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
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM