Mongoose DB监视特定属性更改
在我正在探索的一个Mean stack应用程序中,遇到了一个问题,即需要根据数组属性的长度对存储的文档进行排序Mongoose DB监视特定属性更改,mongoose,mean-stack,mongoose-schema,Mongoose,Mean Stack,Mongoose Schema,在我正在探索的一个Mean stack应用程序中,遇到了一个问题,即需要根据数组属性的长度对存储的文档进行排序 var UserSchema = new Schema({ name: String, email: { type: String, lowercase: true }, role: { type: String, default: 'user' }, password: S
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()}
});
我想让你们注意照片阵列和光电计数
想要为1个属性(在本例中为照片)实现预保存挂钩
然而,据我所知,我能想到的唯一解决方案是添加一个pre-save钩子,它还可以监视所有其他属性。我试图只观察一个属性来更新photoCount,它为照片数组的长度计数存储一个简单的整数值
有人知道我应该阅读的资源吗?您可以使用预保存挂钩,只有在照片阵列发生更改时才更新photoCount:
UserSchema.pre('save', function (next) {
if (this.isModified('photos')) {
this.photoCount = this.photos.length;
}
next();
});
没问题。很高兴我能帮忙。