I'm building an app with Node and MongoDB and I have a company model and an API key model that look like this in Mongoose:
var APIKeysSchema = new Schema({
name: { type: String }
});
var CompanySchema = new Schema({
name : {type : String, required: true, index: { unique: true }}
, apiKeys : [ APIKeysSchema ]
, created_at : {type : Date, default : Date.now}
});
I'd like every company to have by default one API key generated when the company is created. Should I write custom middleware for this, or is there some way to do it within the schema itself. Thanks!
Ended up just doing it as middleware on save in the model:
CompanySchema.pre('save', function(next){
if(this.get('apiKeys').length < 1){
//generate API key
var objectId = new ObjectID();
this.get('apiKeys').push({ key: objectId.toHexString() });
}
next();
});