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

Array validation getting failed because of the "schema" key inside the Schema #12480

Closed
2 tasks done
sourabhbagrecha opened this issue Sep 28, 2022 · 1 comment · Fixed by #12569
Closed
2 tasks done
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@sourabhbagrecha
Copy link

sourabhbagrecha commented Sep 28, 2022

Prerequisites

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

Mongoose version

6.2.2

Node.js version

16.14.2

MongoDB server version

4.4.6

Description

Hi Team,
I have observed a bug in the schema class/validator provided by mongoose. When a schema definition contains a key named: schema and another key containing an array of documents, the validation gets failed even with completely valid documents.

Steps to Reproduce

Step 1. Defining a schema that contains a key named schema and another key that embeds an array.

const AuthorSchema = new Schema({
  fullName: { type: "String", required: true },
});

const BookSchema = new Schema({
  schema: { type: "String", required: true },
  title: { type: "String", required: true },
  authors: [AuthorSchema],
});

const Book = model("book", BookSchema);

Step 2. Insert a document in the collection

  const book = await Book.create({
    schema: "design",
    authors: [{ fullName: "Sourabh Bagrecha" }],
    title: "The power of JavaScript",
  });

Step 3. Which throws the following error:

mongoose/node_modules/mongoose/lib/document.js:3055
    this.$__.validationError = new ValidationError(this);
                               ^

ValidationError: book validation failed: authors: Cast to Array failed for value "[ { fullName: 'Sourabh Bagrecha' } ]" (type Array) at path "authors" because of "TypeError"
    at model.Document.invalidate (/Users/sourabh/Work/repro/mongoose/node_modules/mongoose/lib/document.js:3055:32)
    ...call stack clipped...
    {
  errors: {
    authors: CastError: Cast to Array failed for value "[ { fullName: 'Sourabh Bagrecha' } ]" (type Array) at path "authors" because of "TypeError"
        at model.$set (/Users/sourabh/Work/repro/mongoose/node_modules/mongoose/lib/document.js:1417:9)
        ...call stack clipped...  
      {
      stringValue: `"[ { fullName: 'Sourabh Bagrecha' } ]"`,
      messageFormat: undefined,
      kind: 'Array',
      value: [ { fullName: 'Sourabh Bagrecha' } ],
      path: 'authors',
      reason: TypeError: doc.schema.path is not a function
          at new MongooseDocumentArray (/Users/sourabh/Work/repro/mongoose/node_modules/mongoose/lib/types/DocumentArray/index.js:60:47)
          ...call stack clipped...
      valueType: 'Array'
    }
  },
  _message: 'book validation failed'
}

Note that the validation error does not occur when:

  • The field schema is removed
  • The field schema is renamed to Schema (uppercase S)
  • The array field is removed

The validation error occurs only when both the schema field AND the array field exist in the schema

Step 4. Now if we update the schema by uppercasing the key Schema from lowercased schema

  const BookSchema = new Schema({
    Schema: { type: "String", required: true },
// ^^^^^^^
    title: { type: "String", required: true },
    authors: [AuthorSchema],
  });

  const book = await Book.create({
    Schema: "design",
// ^^^^^^^
    authors: [{ fullName: "Sourabh Bagrecha" }],
    title: "The power of JavaScript",
  });

Step 5. It will work completely fine if schema was spelled differently (e.g. with an uppercase S, i.e.: Schema)

{
  "Schema": "design",
  "title": "The power of JavaScript",
  "authors": [
    {
      "fullName": "Sourabh Bagrecha",
      "_id": new ObjectId("633343a2396c4534d5a70e19")
    }
  ],
  "_id": new ObjectId("633343a2396c4534d5a70e18"),
  "__v": 0
}

Expected Behavior

I understand that schema is a reserved keyword that can be used to fetch the document's schema.
image

But in that case, it should throw a warning(compile-time) while we are specifying the schema key in our schema definition. Also, the validation is only throwing the error, when we are specifying an embedded array of documents in our definition. In all the other cases, having the schema key in our definition doesn't throw any validation error at the time of insert/update.

The expected behavior IMO would be a consistent error irrespective of the embedded array.

@IslandRhythms
Copy link
Collaborator

const mongoose = require('mongoose');

const {Schema} = mongoose;

const AuthorSchema = new Schema({
    fullName: { type: "String", required: true },
  });
  
  const BookSchema = new Schema({
    schema: { type: "String", required: true },
    title: { type: "String", required: true },
    authors: [AuthorSchema],
  }, {supressReservedKeysWarning: true});
  
  const Book = mongoose.model("book", BookSchema);

  async function run() {
    await mongoose.connect('mongodb://localhost:27017');
    await mongoose.connection.dropDatabase();

    const book = await Book.create({
        schema: "design",
        authors: [{ fullName: "Sourabh Bagrecha" }],
        title: "The power of JavaScript",
      });

      console.log('done');
  }

  run();

@IslandRhythms IslandRhythms added the confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. label Sep 29, 2022
@vkarpov15 vkarpov15 added this to the 6.6.6 milestone Oct 5, 2022
vkarpov15 added a commit that referenced this issue Oct 19, 2022
vkarpov15 added a commit that referenced this issue Oct 20, 2022
fix(document): allow creating document with document array and top-level key named `schema`
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
3 participants