mongoosejs / mongoose-lean-getters

Apply getters on lean() documents: https://mongoosejs.com/docs/tutorials/lean.html
Apache License 2.0
10 stars 15 forks source link

Getters not applied correctly to arrays #30

Closed beltingtt closed 8 months ago

beltingtt commented 1 year ago

Do you want to request a feature or report a bug?

bug

What is the current behavior?

Getters are not being applied correctly to arrays in lean queries. This seems to be have been broken with the release of mongoose@7.5.0 as it is working as expected in mongoose@7.4.5.

If the current behavior is a bug, please provide the steps to reproduce.

import mongoose, { Schema } from "mongoose";
import mongooseLeanGetters from "mongoose-lean-getters";

function upper(value) {
    return value.toUpperCase();
}

const userSchema = new Schema({
    name: {
        type: String,
        get: upper,
    },
    emails: [
        {
            type: String,
            get: upper,
        },
    ],
});

userSchema.plugin(mongooseLeanGetters);

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

const run = async () => {
    await mongoose.connect("mongodb://localhost:27017/test");

    const user = new User({
        name: "one",
        emails: ["two", "three"],
    });
    await user.save();

    const foundUser = await User.findById(user._id, {
        _id: 0,
        name: 1,
        emails: 1,
    }).lean({ getters: true });

    console.log(foundUser); // { name: 'ONE', emails: [ 'two', 'three' ] }
};

run();

Please notice that the upper getter is not being applied to the emails array field:

{ name: 'ONE', emails: [ 'two', 'three' ] }

What is the expected behavior?

The upper getter is applied to the emails array field and the above code logs the following:

{ name: 'ONE', emails: [ 'TWO', 'THREE' ] }

What are the versions of Node.js, mongoose-lean-getters, and Mongoose are you are using? Note that "latest" is not a version.

node: 16.20.2 mongoose: 7.5.2 mongoose-lean-getters: 1.1.0

shawnmcknight commented 1 year ago

Running into this as well. I suspect it was caused by the change to getters on arrays in Automattic/mongoose#13774 which was part of 7.5.0.