[Node.js] Implementing Simple Auto Increment with Mongoose

Tadashi Shigeoka ·  Wed, November 20, 2013

I’ll introduce an auto increment implementation with Node.js + Mongoose.

mongoose | マングース

/**
 * Get code to use for new registration
 *
 * @param {Function} callback(error, code)
 **/
var getNewCode = function (callback){
  var new_code = 1;

  Books.findOne({}, {}, {
    sort: {
      code: -1
    }
  }, function(error, doc){
    if (error) {
      console.error(error.stack || error);
      return callback(error);
    }

    if (!doc || !doc.code) {
      return callback(null, new_code);
    }

    new_code = doc.code + 1;

    return callback(null, new_code);
  });
};

Really, it would be better to manage sequential codes (ids) in a separate model like in the reference article, but I wrote this for cases where that’s not necessary.

Creating a model to manage sequential numbers also increases data linearly and makes maintenance troublesome.

That’s all from the Gemba.