#Calling `.lean()` method on a raw query chain does not work (MongoDB + MongooseAdapter).

7 messages · Page 1 of 1 (latest)

safe goblet
#

Hi there,

I'm using raw db queries to circumvent some poorly optimized payload-constructed queries in my project.

What I get back from those is a Mongoose Document, as expected, which I then need to transform into a POJO in order to use in my Client Components.

The problem is that calling the .lean() method in the query chain does not return a POJO directly.

From Mongoose's docs:

By default, Mongoose queries return an instance of the Mongoose Document class. Documents are much heavier than vanilla JavaScript objects, because they have a lot of internal state for change tracking. Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO.

Example:

const organizations = await payload.db.collections
    .organizations!.find({
      type: {
        $eq: "test",
      },
    })
    .lean();
console.log(organizations)

// result
[
  {
    // These are not valid POJO values
    _id: ObjectId('67b7f289af9a2c580ca7b37b'),
    parent: ObjectId('67b7f1a0841fdc04c596c71b'),
    createdAt: ISODate('2025-02-21T03:27:05.292Z'),
    updatedAt: ISODate('2025-02-21T03:27:05.292Z'),
    // ...
  }
]

// expected
[
  {
    _id: '67b7f289af9a2c580ca7b37b',
    parent: '67b7f1a0841fdc04c596c71b',
    createdAt: '2025-02-21T03:27:05.292Z',
    updatedAt: '2025-02-21T03:27:05.292Z',
    // ...
  }
]

I know I could use JSON stringify/parse, but it just adds additional overhead given that I get tens of thousands of entries back.

Am I missing something? Thanks for taking the time to help me.

atomic vapor
safe goblet
#

Ohh sweet! Is this automatic or do I need to call it manually?

#

I'm running payload 3.34.0* but still get raw Mongoose docs as a result

atomic vapor
#

If you use mongoose directly, you'll need to call it manually