Mongoose JS路径默认生成id

时间:2012-11-29 21:32:05

标签: javascript node.js mongoose

看看以下架构:

var userSchema = new mongoose.Schema({
  fullName: {
    type: String,
    required: true,
    index: true
  },
  activationId: {
    type: mongoose.Schema.ObjectId
  }
});

userSchema.path('activationId').default(function() {
  return new mongoose.Schema.ObjectId.fromString('actvt');
});

关于“activationId”,我想在创建用户后生成一个ID(唯一代码,因为它已经内置了Mongoose,所以优先使用objectID),所以如果我有以下代码:

var newUser = new User({
  fullName: 'Rick Richards'
});

newUser.save(function(error, data){
  console.log(data.activationId); // Should give the activationId
});

但是这个解决方案给了我以下错误:

TypeError: undefined is not a function

1 个答案:

答案 0 :(得分:3)

您可以通过为default构造函数的activationId字段定义ObjectId属性来执行此操作:

var userSchema = new mongoose.Schema({
  fullName: {
    type: String,
    required: true,
    index: true
  },
  activationId: {
    type: mongoose.Schema.ObjectId
    default: mongoose.Types.ObjectId
  }
});