2012-08-15 64 views
0

我建立與節點和MongoDB的應用程序,我有一個像這樣的貓鼬公司模型和API密鑰模式:默認嵌套集合中貓鼬與節點

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

我想每一個公司默認擁有創建公司時生成的一個API密鑰。我應該爲此編寫自定義中間件,還是有一些方法可以在模式本身內部完成。謝謝!

+0

您是否嘗試過加入'默認:'功能'apiKeys'創建你要找的默認項? – JohnnyHK 2012-08-15 22:07:20

+0

我剛剛結束添加中間件 – dshipper 2012-08-16 16:56:43

回答

0

端起來只是做中間件上保存模型:

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(); 
    }); 
+0

每次保存文檔時都不會添加其他條目到'apiKeys'嗎? – JohnnyHK 2012-08-16 17:00:50

+0

是的......事後意識到。將其更改爲添加檢查以查看是否已經存在... – dshipper 2012-08-16 20:17:08