nestjs/mongoose

Allow the use of `refPath` field in the @Prop to use dynamic population.

tbhaxor opened this issue · 2 comments

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

This starts with when I tried to implement audit log service with the following schema using class based technique from @nestjs/mongoose.

@Schema()
export class AuditLog {
   @Prop({type: String, required: true, enum: ["User", "Job"]})
   principalType: "User" | "Job"

   @Prop({type: SchemaTypes.ObjectId, refPath: "principalType", required: true})
   principalType: MongooseRef<User> | MongooseRef<Job>;
}

const AuditLogSchema = SchemaFactory.createForClass(AuditLog)

Now when I tried to create the document with principalType User and principal as object id of the user, it is getting saved. But, on retrieval with population, I am getting null.

const user = await this.userModel.findOne().exec()
console.log(!!user) // true

const audit = await this.auditModel.findOne().populate("principal").exec()
console.log(!!audit) // true
console.log(!!audit.principal) // false
console.log(audit.principalType) // User
console.log(audit.principal) // null

Also tried with getModelToken("User") or getModelToken("Job") and still it is not working. But with the old schema declaration it is working.

const AuditLogSchema = new mongoose.Schema({
   principalType: {type: String, required: true, enum: ["User", "Job"]},
   principal: {type: SchemaTypes.ObjectId, refPath: "principalType", required: true}
});

Now when I tried the old code, it is working

const user = await this.userModel.findOne().exec()
console.log(!!user) // true

const audit = await this.auditModel.findOne().populate("principal").exec()
console.log(!!audit) // true
console.log(!!audit.principal) // true
console.log(audit.principalType) // User
console.log(audit.principal.email === user.email) // true

Describe the solution you'd like

Fix the codebase, so as to fix this issue.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

The class based schema definition is an elegant way and I don't want to go back to old way of mongoose schema declaration.

Please provide a minimum reproduction repository (Git repository/StackBlitz/CodeSandbox project).

As of now it is working while setting up new project, but not working with the old one. Even though all versions are up to date. I don't have enough bandwidth to look into this issue. Therefore closing it as of now.