Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document methods are not available when it is populated #14574

Closed
2 tasks done
viganll opened this issue May 6, 2024 · 1 comment · Fixed by #14581
Closed
2 tasks done

Document methods are not available when it is populated #14574

viganll opened this issue May 6, 2024 · 1 comment · Fixed by #14581
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.

Comments

@viganll
Copy link

viganll commented May 6, 2024

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.3.3

Node.js version

18.17.1

MongoDB server version

5

Typescript version (if applicable)

4.8

Description

After populating a field the document doesn't have the methods available. For instance, I have a user schema that has an instance method fullName. If I try to populate one of the fields of the user schema then typescript complains that the method fullName is not available.

This issue doesn't happen in 8.3.1.

Steps to Reproduce

import mongoose, { HydratedDocument, Model, Schema, Types, model } from "mongoose";

// Document definition
interface User {
  firstName: string;
  lastName: string;
  friend?: Types.ObjectId;
}

interface UserMethods {
  fullName(): string;
}

type UserModelType = Model<User, {}, UserMethods>;

const userSchema = new Schema<User, UserModelType, UserMethods>(
  {
    firstName: String,
    lastName: String,
    friend: { type: Schema.Types.ObjectId, ref: "User" },
  },
  {
    methods: {
      fullName() {
        return `${this.firstName} ${this.lastName}`;
      },
    },
  }
);
const userModel = model<User, UserModelType>("User", userSchema);

const UserModel = () => userModel;

async function run() {
  await mongoose.connect("mongodb://localhost:27017");
  await mongoose.connection.dropDatabase();

  const user1 = await UserModel().create({ firstName: "V", lastName: "B" });
  await UserModel().create({ firstName: "b", lastName: "B", friend: user1._id });

  const user = await UserModel().findOne({ firstName: "b" }).populate<{ friend: HydratedDocument<User, UserMethods> }>("friend").exec();
  if (!user) return;
  user.fullName(); // DOESN'T WORK -> Property 'fullName' does not exist on type
  user.friend?.fullName(); // works
}

run();

Expected Behavior

I would expect that there is no typescript errors and methods to be available even after populating a field.

@IslandRhythms IslandRhythms added the confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. label May 7, 2024
@IslandRhythms
Copy link
Collaborator

const mongoose = require('mongoose');



const userSchema = new mongoose.Schema(
  {
    firstName: String,
    lastName: String,
    friend: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
  },
  {
    methods: {
      fullName() {
        return `${this.firstName} ${this.lastName}`;
      },
    },
  }
);
const userModel = mongoose.model("User", userSchema);

const UserModel = () => userModel;

async function run() {
  await mongoose.connect("mongodb://localhost:27017");
  await mongoose.connection.dropDatabase();

  const user1 = await UserModel().create({ firstName: "V", lastName: "B" });
  await UserModel().create({ firstName: "b", lastName: "B", friend: user1._id });

  const user = await UserModel().findOne({ firstName: "b" }).populate("friend");
  if (!user) return;
  console.log('user.friend.fullName()', user.friend.fullName())
  console.log('user.fullName()', user.fulllName())
  user.fullName(); // DOESN'T WORK -> Property 'fullName' does not exist on type
  user.friend?.fullName(); // works
}

run();

vkarpov15 added a commit that referenced this issue May 9, 2024
vkarpov15 added a commit that referenced this issue May 9, 2024
types(model+query): pass TInstanceMethods to QueryWithHelpers so populated docs have methods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Projects
None yet
2 participants