2017-06-16 38 views
2

在正在探索的Mean stack應用程序中,遇到了需要按數組屬性的長度對存儲的文檔進行排序的問題。Mongoose DB手錶特定屬性更改

var UserSchema = new Schema({ 
    name: String, 
    email: { 
     type: String, 
     lowercase: true 
    }, 
    role: { 
     type: String, 
     default: 'user' 
    }, 
    password: String, 
    provider: String, 
    salt: String, 
    facebook: {}, 
    photos:[String], 
    photoCount: Number, 
    plants:[{type: mongoose.Schema.Types.ObjectId, ref : 'Plant'}], 
    imgurAlbumID: String, 
    createdAt : {type:Date, default: new Date()} 

}); 

我會想提醒您注意照片陣列和PHOTOCOUNT

想要實現一個屬性的前保存鉤子,在這種情況下,照片

但是,從我所知道的情況來看,我能想到的唯一解決方案是添加一個預存儲鉤子,以監視所有其他屬性。我試圖只觀察1個單一屬性來更新photoCount,它存儲一個簡單的Integer值,用於照片數組的長度計數。

有誰知道我應該閱讀的資源?

回答

2

您可以使用預先保存鉤且僅當照片陣列已經改變更新PHOTOCOUNT:

UserSchema.pre('save', function (next) { 
    if (this.isModified('photos')) { 
     this.photoCount = this.photos.length; 
    } 
    next(); 
}); 
+0

這個偉大的工程,感謝史蒂夫。 –

+0

沒問題。很高興我能幫上忙。 –

+0

你是否能夠接受這個答案? –