arashsheyda / nuxt-mongoose

A Nuxt module for simplifying the use of Mongoose in your project.
https://docs.arashsheyda.me/nuxt-mongoose
75 stars 13 forks source link

How to add plugins #60

Closed lea0o0oo closed 3 months ago

lea0o0oo commented 3 months ago

How can I attach plugins to my schema?

I want to add pagination with mongoose-paginate-v2, but the .plugin() function does not exist in the schema

import { defineMongooseModel } from "#nuxt/mongoose";
import { Schema } from "mongoose";
import mongoosePaginate from "mongoose-paginate-v2";

export const ProjectSchema = defineMongooseModel({
  name: "Project",
  schema: {
    name: {
      type: String,
      required: true,
    },
    type: {
      type: String,
      required: true,
    },
    //@ts-ignore
    lastModified: {
      type: Date,
      default: () => Date.now(),
    },
    projectRef: {
      type: Schema.ObjectId,
      required: true,
    },
  },
});

ProjectSchema.plugin(mongoosePaginate); // Error: ProjectSchema.plugin is not a function
arashsheyda commented 3 months ago

@lea0o0oo have you tried adding it in hooks? like

export const ProjectSchema = defineMongooseModel({
  name: "Project",
  schema: {
    ...
  },
  hooks(schema) {
    schema.plugin(mongoosePaginate)
  },
});
lea0o0oo commented 3 months ago

It works! Thank you so much, and sorry for the inconvenience

arashsheyda commented 3 months ago

@lea0o0oo glad it works oh no worries at all! you can always open an issue no matter what

lea0o0oo commented 3 months ago

Now, the problem are types, it doesent know what Schema.paginate does. Is there a way to make it know what it is?

pheng0077 commented 1 month ago

is there any example for typescript support with mongoose-paginate-v2?

arashsheyda commented 1 month ago

sorry not that I know of