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

flattenObjectIds toObject option side effects #13648

Closed
2 tasks done
stevemit007 opened this issue Jul 24, 2023 · 1 comment · Fixed by #13658
Closed
2 tasks done

flattenObjectIds toObject option side effects #13648

stevemit007 opened this issue Jul 24, 2023 · 1 comment · Fixed by #13658
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.

Comments

@stevemit007
Copy link

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.

@IslandRhythms IslandRhythms added the confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. label Jul 24, 2023
@IslandRhythms
Copy link
Collaborator

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

interface IUser {
  name: string;
}
const UserSchema = new Schema<IUser>(
  {
    name: String
  },
  {
    toObject: { flattenObjectIds: true }
  }
);
const User: Model<IUser> = model("User", UserSchema);
async function run() {
  await connect('mongodb://localhost:27017');
  await connection.dropDatabase();
  User.create({ name: "George" }).then((d) => {
    User.findById(d._id)
      .exec()
      .then((d) => console.log(d));
  });
}

run();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants