I need an auto increment field, but not for the primary id, it's only to provide an easy to remember case number to the users of a customers support application.
I found this article that explain how to create an auto increment field on mongodb http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/ but this solutions are not supported on minimongo yet.
How can I implement this feature? I don't care if the solutions skip some consecutive case numbers due to errors, but the case number must be unique.
Is there another approach to generate unique and short case numbers? I don't want to give to the users a case code like this PxyooJWSKc3sMz6Lc, because they must refer to their issues with the case number.
Edit:
Minimong doesn't support findAndModify, so I can't use the first solution listed on the link I posted. The second solution also require methods not available on minimongo.
Using the mongo-counter package, is posible to create an incrementer with the method incrementCounter(name)
. The implementation is based on Create an Auto-Incrementing Sequence Field accessing directly the database without going through a Meteor Collection.
Meteor.methods({
'addRecord':function(doc) {
doc.id = incrementCounter('docId');
MyCollection.insert(doc);
return doc.id;
}
});
Update
There are new mongo counter packages on Atmosphere, probably better than my initial recommendation.
Well there are a couple of ways you can do this. If you need it to be absolutely consistent you could store the current integer in your collection & use a Meteor.call to add a new record as opposed to doing it from the client.
E.g
Server side js
Meteor.methods({
'addRecord':function(doc) {
currentId = MyCollection.findOne({},{sort:{id:-1}}).id || 1;
doc.id = currentId + 1;
MyCollection.insert(doc);
return doc.id;
}
});
Client side js
doc = {name:"Bob"}
//MyCollection.insert(doc)
//Use this instead
Meteor.call("addRecord", doc, function(err,result) {
if(result) {
console.log("Successfully added new record with auto_inc id " + result);
}
}
Doing it with the Meteor.call you would lose one thing though: latency compensation.
You could store something that is built from a Unix timestamp and shorten it to something more applicable (e.g by cutting off the first few digits):
new Date().getTime().toString().substr(4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With