-
Hi, I'm migrating my codebase from Mongoose to Typegoose and have a problem. Can you help please? I need to add few custom field to mongoose instance without export class UserSchema {
@prop({
required: false,
type: [String],
enum: _.keys(constants.roles.global),
hideJSON: true,
})
public roles?: Types.Array<string>
public __dynamicRoles: string[] = []
public get allRoles() {
return _.union(this.__dynamicRoles, this.roles)
}
public addDynamicRoles(this: DocumentType<UserSchema>, ...roles) {
console.log('>>>>>> this.__dynamicRoles', this.__dynamicRoles) // It's always `undefined`
this.__dynamicRoles = [...this.__dynamicRoles, ...roles]
}
}
export const User = getModelForClass(UserSchema)
// ....
const user = await User.findById('some-id')
user.addDynamicRoles(['guest', 'everyone'])
// TypeError: this.__dynamicRoles is not iterable This approach works fine with Mongoose, but not with Typegoose. It's there a way to achieve such behaviour or did I've missed something? Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I think you are expecting your non-prop field to have a default value, which will not work because mongoose does not "officially" support such properties and so typegoose does not translate any properties that do not have a The reason why typegoose also does not support it is because the documents / models are not actually instances of the class you have created, classes in typegoose are basically just a combined place to have options, types and runtime schema. |
Beta Was this translation helpful? Give feedback.
I think you are expecting your non-prop field to have a default value, which will not work because mongoose does not "officially" support such properties and so typegoose does not translate any properties that do not have a
@prop
on them.The reason why typegoose also does not support it is because the documents / models are not actually instances of the class you have created, classes in typegoose are basically just a combined place to have options, types and runtime schema.