-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
Labels
confirmed-bug
We've confirmed this is a bug in Mongoose and will fix it.
Comments
IslandRhythms
added
the
confirmed-bug
We've confirmed this is a bug in Mongoose and will fix it.
label
May 7, 2024
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
types(model+query): pass TInstanceMethods to QueryWithHelpers so populated docs have methods
This was referenced Jun 5, 2024
This was referenced Jun 22, 2024
This was referenced Jun 24, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prerequisites
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 methodfullName
is not available.This issue doesn't happen in 8.3.1.
Steps to Reproduce
Expected Behavior
I would expect that there is no typescript errors and methods to be available even after populating a field.
The text was updated successfully, but these errors were encountered: