Skip to content

Populate + lean + multiple populated documents leads to "Cannot read properties of undefined (reading '_id')" in version 8.5.2 #14794

Closed

Description

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.5.2

Node.js version

22

MongoDB server version

7.0

Typescript version (if applicable)

No response

Description

Populating with 'lean' and more then one model in a populated object cause in error in v8.5.2. All works fine i v.8.5.1. Without lean() all works fine too

Error: TypeError: Cannot read properties of undefined (reading '_id')
    at _assign (//node_modules/mongoose/lib/model.js:4471:38)
    at _done (/node_modules/mongoose/lib/model.js:4300:9)
    at _next (//node_modules/mongoose/lib/model.js:4288:7)
    at //node_modules/mongoose/lib/model.js:4396:7
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Looks like it happens because of 7c2cfa8#diff-305dbcc98ad8fc959dd0c0be51280893962af34c2d8b18abc871cffc2d80c5f9R4471 as part of fix #14759

Steps to Reproduce

This an abstract sample how to reproduce it

import mongoose from "mongoose";

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

const authorSchema = new mongoose.Schema({
  group: String, // our populate key
  name: String,
});

const postSchema = new mongoose.Schema({
  authorGroup: String,
  title: String,
  content: String,
});

const Author = mongoose.model("Author", authorSchema);
const Post = mongoose.model("Post", postSchema);

async function createTestData() {
  await Author.create({ group: "AUTH1", name: "John Doe" });
  await Author.create({ group: "AUTH2", name: "Jane Smith" });
  await Author.create({ group: "AUTH2", name: "Will Jons" }); // second author with the same group (it will cause an issue). One populated record works just fine

  await Post.create({
    authorGroup: "AUTH1",
    title: "First Post",
    content: "Content 1",
  });
  await Post.create({
    authorGroup: "AUTH2",
    title: "Second Post",
    content: "Content 2",
  });
}

async function runProblemQuery() {
  try {
    const posts = await Post.find()
      .populate({
        path: "authorGroup",
        model: "Author",
        select: { _id: 1, name: 1 },
        foreignField: "group",
      })
      .select({ _id: 1, authorGroup: 1, title: 1 })
      .lean();

    /**
     * WARNING: Bug detected in Mongoose 8.5.2 when using .lean() with .populate()
     *
     * Issue: When using .lean() in combination with .populate() and a custom foreignField,
     * Mongoose fails to correctly populate the related documents.
     */
    console.log(
      "postPopulate>>>>>>",
      JSON.stringify(posts, null, 2)
    );
  } catch (error) {
    console.error("Error:", error);
  }
}

async function runTest() {
  await createTestData();
  await runProblemQuery();
  mongoose.connection.close();
}

runTest();

Expected Behavior

Code return data

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions