Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?.

like image 888
Sebastián Espinosa Avatar asked Apr 07 '14 03:04

Sebastián Espinosa


1 Answers

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();
  });
});
like image 118
Gilberto Avalos Avatar answered Oct 14 '22 13:10

Gilberto Avalos