Mongoose: Get max id from table before inserting new row


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?

Problem courtesy of: lostintranslation


Here is a link that i found that does exactly what I need to do. Even gives a couple of options.

Solution courtesy of: lostintranslation


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.

Discussion courtesy of: JohnnyHK

This recipe can be found in it's original form on Stack Over Flow.