在mongoose的字段中将函数定义为默认值

时间:2014-04-07 03:53:42

标签: javascript node.js mongodb express mongoose

我想做这样的事情:

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

这是可能的吗?

1 个答案:

答案 0 :(得分:8)

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();
  });
});