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

Fix document not applying manual populate when using a function in schema.options.ref #15138

Merged
merged 2 commits into from
Jan 4, 2025

Conversation

IchirokuXVI
Copy link
Contributor

Summary

Schema.options.ref works with functions but it doesn't mark the path as populated if done manually when creating a new document or assigning to a property.

Examples

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017");

const test = async () => {
  const userSchema = new mongoose.Schema({
    username: { type: String },
    phone: { type: mongoose.Schema.Types.ObjectId, ref: "phones" },
  });

  const userSchemaWithFunc = new mongoose.Schema({
    username: { type: String },
    phone: {
      type: mongoose.Schema.Types.ObjectId,
      ref: function () {
        return "phones";
      },
    },
  });

  const phoneSchema = new mongoose.Schema({
    phoneNumber: { type: String },
    extension: { type: String },
  });

  const User = mongoose.model("users", userSchema);
  const UserWithFunc = mongoose.model("usersWithFunc", userSchemaWithFunc);
  const Phone = mongoose.model("phones", phoneSchema);

  const phone = await Phone.create({
    phoneNumber: "123456789",
    extension: "123",
  });

  const user = await User.create({
    username: "John Doe",
    phone,
  });

  const userWithFunc = await UserWithFunc.create({
    username: "John Doe",
    phone,
  });

  console.log(user.populated("phone")); // Returns ObjectId
  console.log(userWithFunc.populated("phone")); // Returns undefined
};

test()
  .then(() => console.log("Finished"))
  .catch((error) => console.error(error))
  .finally(() => process.exit(0));

Copy link
Collaborator

@vkarpov15 vkarpov15 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I made a couple of minor changes to make this more consistent with ref function checks in other places, but otherwise LGTM. I'll add a test after merging.

@vkarpov15 vkarpov15 merged commit 5dcca7e into Automattic:master Jan 4, 2025
38 checks passed
@vkarpov15 vkarpov15 added this to the 8.9.4 milestone Jan 4, 2025
vkarpov15 added a commit that referenced this pull request Jan 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants