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 trialGary Lau
2,307 PointsHow 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
2 Answers
Seth Kroger
56,413 PointsPerhaps 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.)
Gary Lau
2,307 PointsHi 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
56,413 PointsThe 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');
Gary Lau
2,307 PointsGary Lau
2,307 PointsBelow is my sample code. I stored the client shortname and sequence number in a separated collection 'Client' though.