Use other model inside useFactory in Nest.Js

1.4k Views Asked by At

How to use other model inside useFactory ?

I want to query by other model before or after save. But i don't know how to achieve this in @nestjs/mongoose.

check example code below for reference.

    MongooseModule.forFeatureAsync([
      {
        name: Post.name,
        useFactory: () => {
          PostSchema.pre('save', () => {
            // Use other mode for query
            // For Examole
            // UserModel.findOne({})
            console.log('Hello from pre save');
          });
          return PostSchema;
        },
      },
    ]),
2

There are 2 best solutions below

2
On

You can inject the model you need when using factories. Something like:

MongooseModule.forFeatureAsync({
    name: Post.name,
    inject: [getModelToken(User.name)],
    import: [MongooseModule.forFeature(User.name)],
    useFactory: (userModel) => {
        PostSchema.pre('save', () => {
            // Use other model for query
            // For Examole
            userModel.findOne({})
            console.log('Hello from pre save');
        });
        return PostSchema;
    }
}
0
On

Maybe there is a typing mistake with @Agus Neira answer, I thing the correct is:

MongooseModule.forFeatureAsync({
name: Post.name,
inject: [getModelToken(User.name)],
import: [
    MongooseModule.forFeature([{name: User.name, schema: UserSchema}])// Should be arr
], 
useFactory: (userModel) => {
    PostSchema.pre('save', () => {
        // Use other model for query
        // For Examole
        userModel.findOne({})
        console.log('Hello from pre save');
    });
    return PostSchema;
}

}