Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.97k stars 3.84k forks source link

Field setter miss the second fieldSchema argument after migration from 5 to 6 mongoose version #11716

Closed tyz-crazy closed 2 years ago

tyz-crazy commented 2 years ago

Do you want to request a feature or report a bug? feature . Missing functionality after 5 to 6 mongoose version migration If the current behavior is a bug, please provide the steps to reproduce. In mongoose 5.13.9 when you used the setter for the field, the second argument in the setter function was field description schema, now in mongoose 6.3.1 the second argument is missing.

It was very convenient to have fieldSchema as second argument and use it in some common setter whic used for few fields. Use case: Use function schemaFieldSetter for few fields in the schemas, and nested schemas and fields, for pre save some previous values and use it after it hooks.

const schemaFieldSetter = function (newValue, fieldSchema) {
    if (!lodash.isPlainObject(this.$prevValues)) {
        this.$prevValues = {};
    }

    if (this[fieldSchema.path] !== newValue) {
        this.$prevValues[fieldSchema.path] = this[fieldSchema.path];
    }

    return newValue;
}

Without fieldSchema argument it impossible to determinate the field path and impossible to use common setters withour additional workarounds. Can you please restore the fieldSchema for setters. Thanks

IslandRhythms commented 2 years ago

So the field description is now the third argument and the prior val is the second. https://mongoosejs.com/docs/migrating_to_6.html#schematype-set-parameters

const mongoose = require('mongoose');

const {Schema} = mongoose;

const userSchema = new Schema({
email: {
    type: String,
    set: (v, descrip, third) => {
        console.log('the second parameter', descrip)
        console.log('the third parameter', third)
        v.toLowerCase()
    }
}
});

const User = mongoose.model('User', userSchema);

async function run() {
    await mongoose.connect('mongodb://localhost:27017/test');
    await mongoose.connection.dropDatabase();

    const user = await User.create({ email: 'TEST@gmail.com' });
    user.email; // 'test@gmail.com'

    // The raw value of `email` is lowercased
    user.get('email', null, { getters: false }); // 'test@gmail.com'

    user.set({ email: 'NEW@gmail.com' });
    user.email; // 'new@gmail.com'
}

run();
tyz-crazy commented 2 years ago

Oops, I must have missed it when reading the documentation. My mistake, thanks!