【问题标题】:Mongoose DB watch specific attribute changeMongoose DB 观察特定属性变化
【发布时间】:2017-11-18 18:27:55
【问题描述】:

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

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

});

我想请您注意 photos 数组和 photoCount

想要只为 1 个属性实现预保存挂钩,在本例中为 photos

但是,据我所知,我能想到的唯一解决方案是添加一个同时监视所有其他属性的预保存挂钩。我试图只关注 1 个单一属性来更新 photoCount ,该属性存储 photos 数组长度计数的简单整数值。

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

【问题讨论】:

    标签: mongoose mean-stack mongoose-schema


    【解决方案1】:

    您可以使用预保存挂钩,并且仅在照片数组已更改时才更新 photoCount:

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

    【讨论】:

    • 没问题。很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 2011-05-27
    • 1970-01-01
    • 2018-04-10
    • 2013-10-24
    • 2017-09-07
    • 2017-04-08
    • 2017-09-13
    相关资源
    最近更新 更多