1

Take a look at the following schema:

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

It is about the "activationId", I want to generate an ID (unique code, objectID prefered since that is already built-in Mongoose) once a user gets created, so if I have the following code:

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

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

But this solution gives me the following error:

TypeError: undefined is not a function
4

1 回答 1

3

您可以通过为作为构造函数的字段定义一个default属性来做到这一点:activationIdObjectId

var userSchema = new mongoose.Schema({
  fullName: {
    type: String,
    required: true,
    index: true
  },
  activationId: {
    type: mongoose.Schema.ObjectId
    default: mongoose.Types.ObjectId
  }
});
于 2012-11-29T22:21:06.240 回答