Auto increment a number field in mongoose model Auto increment a number field in mongoose model mongoose mongoose

Auto increment a number field in mongoose model


I will recommend second approach for you.

EmborderSchema.pre('save', function (next) {  var self = this;  if (self.emborder_id == undefined) {    Emborder.findOne({})      .sort({emborder_id: -1})      .exec(function (err, data) {        if(!data.emborder_id){         self.emborder_id = 1;         next();        }else{          self.emborder_id = data.emborder_id + 1;          next();        }      })    next();  }});

For more you can read about Context in javascript.

For example, inside of a function, when you say: “this.accoutNumber”, you are referring to the property “accoutNumber”, that belongs to the object within which the function is executing.

If the object “foo” has a method called “bar”, when the JavaScript keyword “this” is used inside of “bar”, it refers to “foo”. If the function “bar” were executed in the global scope, then “this” refers to the window object.

Context example taken from --> https://blog.kevinchisholm.com/javascript/difference-between-scope-and-context/