Skip to content

Error/warn if default is the wrong type #9232

@JosephScript

Description

@JosephScript

Do you want to request a feature or report a bug?

Bug? Might be just unclear from the docs.

What is the current behavior?

Let's say you have two models, and one has an array of the other. You use ObjectId in an array. There are two ways to define this from what I can see:

// classroom.js
import { Schema, model } from 'mongoose'
const ClassroomSchema = new Schema(
  {
    name: { type: String, required: true, trim: true },
    students: {
      type: [Schema.Types.ObjectId],
      ref: 'Person',
      default: [],
    },
  },
)
  .set('toJSON', { virtuals: true })
export default model('Classroom', ClassroomSchema)

And:

// classroom.js
import { Schema, model } from 'mongoose'
const ClassroomSchema = new Schema(
  {
    name: { type: String, required: true, trim: true },
    students: [{
      type: Schema.Types.ObjectId,
      ref: 'Person',
      default: [],
    }],
  },
)
  .set('toJSON', { virtuals: true })
export default model('Classroom', ClassroomSchema)

If the current behavior is a bug, please provide the steps to reproduce.

When I use the first version of the schema, and create documents, then switch to the second version I can no longer load those documents. Are these underlyingly different? Is this a bug or expected?

What is the expected behavior?
I would expect them to behave the same.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

Node v14.1.0, Mongoose v5.8.11, MongoDB 4.0.14 Community.

Metadata

Metadata

Assignees

No one assigned

    Labels

    developer-experienceThis issue improves error messages, debugging, or reportingdocsThis issue is due to a mistake or omission in the mongoosejs.com documentationenhancementThis issue is a user-facing general improvement that doesn't fix a bug or add a new feature

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions