Search code examples
mongoosenestjsmongoose-schemamongoose-models

How can I use the mongoose model without initializing in the constructor in nestjs?


I was using the mongoose schema injection in the service as we normally do. But now i wish to transfer some of my code to a helper function so that it can be reused. Generally, mongoose schema is injected as:-

export class UsersService {
  constructor(
    private postsService: PostsService,
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @InjectModel(Category.name) private categoryModel: Model<AddCategoryDto>,
    @InjectModel(friendship.name)
    private friendshipModel: Model<friendshipDocument>,
    @InjectModel(Attachment.name)
    private attachmentModel: Model<AttachmentDocument>,
    @InjectModel(UserCategory.name)
    private userCategoryModel: Model<AddUserCategoryDto>,
    @InjectModel(Post.name) private postModel: Model<PostDocument>,
    @InjectModel(Image.name) private imageModel: Model<ImageDocument>,
  ) {}}

So, now I want this @InjectModel(User.name) private userModel: Model<UserDocument> to use in a function definition in a separate file, like this:-

export isFriends(userID: string, friendID: string){
   @InjectModel(User.name) private userModel: Model<UserDocument>
   const user1 = await userModel.findById(userID);
}

But I get error at this time. Please tell me, how this can be achieved? Somewhat fresher in NESTJS.


Solution

  • The closest thing to what you want to achieve is to simply pass userModel into function's parameters (I also passed args as object because it's not good to have a bunch of unnamed arguments):

    export async function isFriends({
        userID,
        friendID,
        userModel,
    }: {
        userID: string;
        friendID: string;
        userModel: Model<UserDocument>;
    }) {
        const user1 = await userModel.findById(userID);
    }