Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How can I create a customized auto increase field in Mongodb?

Hi,

I am using Node.js and Mongoose. Is there anyway to create a customized auto increasing field like 'member id'?

The 'member id' is in the format of two letters followed by 4 digits. i.e. 'CS0001'. The letters represent the client name. This 'member id' need to auto increase for any new record. i.e. 'CS0002', 'DT0001', etc.

I tried to query the collection to find the latest 'member id' of this client name. However since Node.js is stateless and single threaded, the callback function will always invoked after I insert the new record. This information is just not available when I need it.

Please share your opinion and thoughts.

Cheers, Gary

Below is my sample code. I stored the client shortname and sequence number in a separated collection 'Client' though.

        function getNextSeqenceNo ( client ) {
            var promise = Client.findOne( { name: client } ).exec();
            return promise;
        }

        var memberId = '';
        var promise = getNextSeqenceNo( req.body.client );
        promise.then( function(client) {
            memberId = client.shortName + client.seqNo++;  // ** this line was invoked after cust.save() below
        });

        var cust = new Customer( req.body );

        cust.memberId = memberId;   // ** memberId = ''

        cust.save(function(err) {
            if (err)
                res.send(err);

            res.json( { message: 'Member created!' } );
        });

2 Answers

Seth Kroger
Seth Kroger
56,413 Points

Perhaps the simplest solution is best here. If you want to increment the member number before saving the Customer record, then don't save the record until after the member number is incremented. (Since you also mention mongoose, you could also define a "pre save" hook on your schema to create a member id if none exists.)

Hi Seth,

Thank you! I need to do more research on 'pre save' function in mongoose. But I am able to get this working by putting the cust.save() into the callback function of promise. That is to assign the sequence number before it get saved.

Another question is (may off topic), I am trying to deploy this to a server. However the mongoose connection string is still using 'localhost'. Would that work automatically or I must change it to the absolute path of the mongodb server?

Thanks, Gary

Seth Kroger
Seth Kroger
56,413 Points

The exact details will depend on where you deploy to, but generally you'll set "environment variables" to specify things like database connections and server ports. You can access these in node through process.env:

// Use the environment variable MONGO_URI if set, otherwise use localhost
mongoose.connect(process.env.MONGO_URI || 'mongodb://localhost/myDb');