Skip to content

Instantly share code, notes, and snippets.

@lukejagodzinski
Last active June 26, 2016 04:07
Show Gist options
  • Save lukejagodzinski/32d834053620f0b71397 to your computer and use it in GitHub Desktop.
Save lukejagodzinski/32d834053620f0b71397 to your computer and use it in GitHub Desktop.
Auto increment field using Astronomy
var autoIncSave = function(doc, fieldName) {
while (true) {
var Class = doc.constructor;
var Collection = Class.getCollection();
var sort = {};
var fields = {};
sort[fieldName] = -1;
fields[fieldName] = 1;
var max = Collection.findOne({}, {
sort: sort,
fields: fields,
transform: null
})[fieldName];
var next = max + 1;
try {
doc.set(fieldName, next);
doc.save();
break;
} catch (e) {
if (e.name === 'MongoError' && e.code === 11000) {
continue;
}
}
}
};
Items = new Mongo.Collection('items');
Item = Astro.Class({
name: 'Item',
collection: Items,
fields: {
order: 'number'
},
indexes: {
order: {
fields: {
order: 1
},
options: {
unique: true
}
}
}
});
var item = new Item();
autoIncSave(item, 'order');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment