Making Plugin Effects Extend to Model Discriminations?

Hi, everyone.

I have this file:

const mongoose = require("mongoose");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const Schema = mongoose.Schema;
const { TaskSchema } = require("./task");

const Session = new Schema({
  refreshToken: { type: String, default: "" }
});

const UserSchema = new Schema({
  firstName: { type: String, default: "" },
  lastName: { type: String, default: "" },
  email: { type: String, default: "" },
  authStrategy: { type: String, default: "local" },
  refreshToken: { type: [Session] }
},
{
  discriminatorKey: "role"
});

// remove refresh token from the response
UserSchema.set("toJSON", {
  transform: (doc, ret, options) => {
    delete ret.refreshToken;
    return ret;
  }
});

UserSchema.plugin(passportLocalMongoose);
const User = mongoose.model("User", UserSchema);

const ChildUser = User.discriminator("child", {
  tasks: { type: [TaskSchema] }
});
const ParentUser = User.discriminator("parent", {
  children: { type: [ChildUser.schema] }
});

ChildUser.schema.plugin(passportLocalMongoose);
ParentUser.schema.plugin(passportLocalMongoose);

module.exports = { User, ParentUser, ChildUser };

I want to know if I can make it so that the effects of the call .plugin(passportLocalMongoose) would also be applied on ParentUser and ChildUser. When I mouse-over on either of them on VS Code right now, it says it’s a regular Model rather than a “Passport Local” Model. User is a “Passport Local” Model, so I can call passport-auth functions like register on it, but that’s not the case for the two “discriminated” ones. I want to be able to call those functions on all three.

So is that not possible?

Hi @Osman_Zakir,

Welcome to the MongoDB Community forums :sparkles:

When creating new models from an existing one using the discriminator method, it’s necessary to apply the plugin to the new models as you have already done and it would presumably work.

I would suggest you call the function and see if you encounter any error messages.

However, for more information on plugins, please refer to the Mongoose documentation

Best,
Kushagra