When I post a request to my node server to create a new item I need to get the max item id from the item table.
I.E. I am using an itemId as a one up sequence in that table.
var Item = new Schema({
itemId: {type: Number, required: true}
...
});
is there a recommended way to get the max itemId such that I can add 1 to it and use that value when I create a new item?
You can get the max itemId via:
ItemModel.findOne().sort('-itemId').exec(function(err, item) {
// item.itemId is the max value
});
However, you can't be sure that the max value doesn't change in between when you query for the max and when you add one to it and use it because another request may come in at the same time that does the same thing.
This is one of the reasons why ObjectIds are preferred for IDs.
Here is a link that i found that does exactly what I need to do. Even gives a couple of options.
http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/