Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an auto increment field on meteor?

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.

like image 642
Camilo Avatar asked Apr 08 '13 18:04

Camilo


2 Answers

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.

like image 162
Camilo Avatar answered Oct 18 '22 05:10

Camilo


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.

Other possibility

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)
like image 30
Tarang Avatar answered Oct 18 '22 05:10

Tarang