onlineracoon
onlineracoon

Reputation: 2970

Mongoose JS path default generating id

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

Upvotes: 1

Views: 1234

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

You can do this by defining a default property for the activationId field that's the ObjectId constructor function:

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

Upvotes: 3

Related Questions