Mongoose DB手表的具体属性改变

时间:2017-06-16 05:26:36

标签: mongoose mean-stack mongoose-schema

在正在探索的Mean堆栈应用程序中,遇到了需要按数组属性的长度对存储的文档进行排序的问题。

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个属性实现预保存挂钩,在本例中为照片

但是,据我所知,我能想到的唯一解决方案是添加一个预保存钩子,它也可以监视所有其他属性。我试图只监视1个单一属性来更新 photoCount ,它存储了照片数组长度计数的简单整数值。

有没有人知道我应该阅读的资源?

1 个答案:

答案 0 :(得分:2)

如果照片数组已更改,您可以使用预保存挂钩并仅更新photoCount:

UserSchema.pre('save', function (next) {
    if (this.isModified('photos')) {
        this.photoCount = this.photos.length;
    }
    next();
});
相关问题