mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
221 stars 36 forks source link

AutoPopulate on type.string #119

Closed Bartas139 closed 4 months ago

Bartas139 commented 4 months ago

Hi, I have schema code like this:

const Role = mongoose.model('Role', roleModel.schema)
const userSchema = mongoose.Schema(
    {
        _id: {
            type: String,
            default: randomUUID
        },
        email: {
            type: String,
            unique: true,
            required: [true, 'email is required']
        },
        password: {
            type: String,
            required: [true, 'password is required']
        },
        roles: [{
            type: mongoose.Schema.Types.String,
            ref: 'Role',
            autopopulate: true
        }]
    },
    {
        timestamps: true
    }
)

userSchema.plugin(require('mongoose-autopopulate'))

And the autopopulate does not work at all. There is no error, but the findOne niether find, or findMany is not populated. I always get just the Array of roles IDs. Is there somethind wrong with my code?

Bartas139 commented 4 months ago

Ok... wierd thing I also use

userSchema.methods.toJSON = function() { const {password, ...rest} = {...this._doc} return rest; }

And for some reason the userSchema.plugin(require('mongoose-autopopulate')) muset be above the methods... Quite dont know why, but now it works