1

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;
        },
      },
    ]),
keval
  • 85
  • 10

2 Answers2

1

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;
    }
}
Agus Neira
  • 435
  • 4
  • 9
  • I tried ` userModel.findOne({})` but not working. – keval May 31 '22 at 12:02
  • You should call findOne with the parameters for the User you're trying to query, and that is specific to your project. Is userModel defined with this example? – Agus Neira May 31 '22 at 12:05
1

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;
}

}