Sebastián Espinosa Sebastián Espinosa - 5 months ago 14
Node.js Question

Define a function as a default in a field in mongoose

I want to do something like this:

var categorySchema = new Schema({
id: {
unique: true,
default: function() {
//set the last item inserted id + 1 as the current value.
}
},
name: String
});


This is posible?.

Answer
var categorySchema = new Schema({
  id     : {
    type : Number
  },
  name   : {
    type : String
  }
});

// Define a pre-save method for categorySchema
categorySchema.pre('save', function(next) {
  var self = this;

  // Example of your function where you get the last ID
  getLastId(function(id){
    // Assigning the id property and calling next() to continue
    self.id = id;
    next();
  });
});