Does Mongoose provide access to previous value of property in pre('save')?

前端 未结 4 739
南笙
南笙 2020-12-14 08:23

I\'d like to compare the new/incoming value of a property with the previous value of that property (what is currently saved in the db) within a pre(\'save\') mi

4条回答
  •  情话喂你
    2020-12-14 08:53

    Honestly, I tried the solutions posted here, but I had to create a function that would store the old values in an array, save the values, and then see the difference.

    // Stores all of the old values of the instance into oldValues
    const oldValues = {};
    for (let key of Object.keys(input)) {
        if (self[key] != undefined) {
            oldValues[key] = self[key].toString();
        }
    
        // Saves the input values to the instance
        self[key] = input[key];
    }
    
    yield self.save();
    
    
    for (let key of Object.keys(newValues)) {
        if (oldValues[key] != newValues[key]) {
           // Do what you need to do
        }
    }
    

提交回复
热议问题