【问题标题】:Define a function as a default in a field in mongoose在猫鼬的字段中定义一个函数作为默认值
【发布时间】:2014-05-19 03:48:29
【问题描述】:

我想做这样的事情:

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

这可能吗?

【问题讨论】:

  • 你会如何使用它?
  • 例如,每次添加新值时,我都可以使用另一个值作为参考来设置 id 值,而无需干预。

标签: javascript node.js mongodb express mongoose


【解决方案1】:
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();
  });
});

【讨论】:

  • 是的,当然,回答评论:)
猜你喜欢
  • 2020-06-23
  • 2021-10-17
  • 2018-12-03
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多