Skip to content

flattenObjectIds toObject option side effects #13648

@stevemit007

Description

@stevemit007

Prerequisites

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

Mongoose version

7.4.0

Node.js version

16.17.0

MongoDB server version

6.0.3

Typescript version (if applicable)

5.1.6

Description

Creating a schema with option

toObject: {
  flattenObjectIds: true
}

has unwanted side effects.

MongoDB Compass shows the autogenerated _id field has type string, and Model.findById() returns null.

A workaround is to use toJSON() instead of toObject().

Steps to Reproduce

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

interface IUser {
  name: string;
}
const UserSchema = new Schema<IUser>(
  {
    name: String
  },
  {
    toObject: { flattenObjectIds: true }
  }
);
const User: Model<IUser> = model("User", UserSchema);
User.create({ name: "George" }).then((d) => {
  User.findById(d._id)
    .exec()
    .then((d) => console.log(d));
});

Expected Behavior

Result is not null.

Metadata

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

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions