Last active
June 26, 2016 04:07
-
-
Save lukejagodzinski/32d834053620f0b71397 to your computer and use it in GitHub Desktop.
Auto increment field using Astronomy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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