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

Mongoose attempting to cast subdocument schema to string #11506

Closed
wcarhart opened this issue Mar 8, 2022 · 2 comments
Closed

Mongoose attempting to cast subdocument schema to string #11506

wcarhart opened this issue Mar 8, 2022 · 2 comments
Labels
enhancement This issue is a user-facing general improvement that doesn't fix a bug or add a new feature
Milestone

Comments

@wcarhart
Copy link

wcarhart commented Mar 8, 2022

Do you want to request a feature or report a bug?
I think a bug, but may just be confused.

What is the current behavior?
I have the following schema with a subdocument:

const award = new mongoose.Schema({
  title: { type: String, required: true },
  issueDate: Date,
}, { _id : false, strict: 'throw' })

const profile = new mongoose.Schema({
  handle: { type: String, required: true, max: 30 },
  ...
  awards: [{ type: award }],
}, { strict: 'throw' })

const Profile = mongoose.model('profile', profile)

I am trying to PATCH the following data via my API on a model created via the above schema:

{
  "awards": [{
    "title": "test award",
    "date": "2022-03-08T18:13:36.433Z"
  }]
}

Using the following JavaScript code:

let updatedProfile = {
  handle: 'test',
  ...
  awards: [ { title: 'test award', date: '2022-03-08T18:13:36.433Z' } ]
}
// omitted try-catch for brevity
await (new Profile(updatedProfile)).validate()
await Profile.findOneAndUpdate(
  { handle: 'test' },
  updatedProfile,
  { upsert: true }
)

But, I get the error Error: Validation failed: awards: Cast to embedded failed for value "..." (type string) from the Profile.validate() step:

Error: Validation failed: awards: Cast to embedded failed for value "{ title: 'test award', date: '2022-03-08T18:13:36.433Z' }" (type string) at path "awards", awards.0: Cast to embedded failed for value "{ title: 'test award', date: '2022-03-08T18:13:36.433Z' }" (type string) at path "awards"
    at ValidationError.inspect (.../node_modules/mongoose/lib/error/validation.js:48:26)
    at internal/per_context/primordials.js:23:32
    at formatValue (internal/util/inspect.js:774:19)
    at inspect (internal/util/inspect.js:336:10)
    at formatWithOptionsInternal (internal/util/inspect.js:2006:40)
    at formatWithOptions (internal/util/inspect.js:1888:10)
    at console.value (internal/console/constructor.js:320:14)
    at console.warn (internal/console/constructor.js:353:61)
    at /Users/wcarhart/code/ethos/routes/api.js:154:12
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  errors: {
    awards: CastError: Cast to embedded failed for value "{ title: 'test award', date: '2022-03-08T18:13:36.433Z' }" (type string) at path "awards"
        at DocumentArrayPath.cast (.../node_modules/mongoose/lib/schema/documentarray.js:483:19)
        at .../node_modules/mongoose/lib/model.js:4305:28
        at .../node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
        at new Promise (<anonymous>)
        at promiseOrCallback (.../node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
        at Mongoose._promiseOrCallback (.../node_modules/mongoose/lib/index.js:1140:10)
        at Function.validate (.../node_modules/mongoose/lib/model.js:4254:23)
        at .../routes/api.js:152:18
        at processTicksAndRejections (internal/process/task_queues.js:93:5) {
      stringValue: `"{ title: 'test award', date: '2022-03-08T18:13:36.433Z' }"`,
      messageFormat: undefined,
      kind: 'embedded',
      value: "{ title: 'test award', date: '2022-03-08T18:13:36.433Z' }",
      path: 'awards',
      reason: [StrictModeError],
      valueType: 'string'
    },
    'awards.0': CastError: Cast to embedded failed for value "{ title: 'test award', date: '2022-03-08T18:13:36.433Z' }" (type string) at path "awards"
        at DocumentArrayPath.cast (.../node_modules/mongoose/lib/schema/documentarray.js:483:19)
        at DocumentArrayPath.cast (.../node_modules/mongoose/lib/schema/documentarray.js:402:17)
        at SchemaType.DocumentArrayPath.$embeddedSchemaType.cast (.../node_modules/mongoose/lib/schema/documentarray.js:75:29)
        at .../node_modules/mongoose/lib/model.js:4305:28
        at .../node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
        at new Promise (<anonymous>)
        at promiseOrCallback (.../node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
        at Mongoose._promiseOrCallback (.../node_modules/mongoose/lib/index.js:1140:10)
        at Function.validate (.../node_modules/mongoose/lib/model.js:4254:23)
        at .../routes/api.js:152:18 {
      stringValue: `"{ title: 'test award', date: '2022-03-08T18:13:36.433Z' }"`,
      messageFormat: undefined,
      kind: 'embedded',
      value: "{ title: 'test award', date: '2022-03-08T18:13:36.433Z' }",
      path: 'awards',
      reason: [StrictModeError],
      valueType: 'string'
    }
  },
  _message: 'Validation failed'

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

What is the expected behavior?
I would not expect this data to fail validation. I've also tried creating a new Date() from awards[0].date but the same error occurred.

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

Mongoose
node -e 'console.log(require("mongoose").version)': 6.2.4

MongoDB
v4.4 on DigitalOcean

@wcarhart
Copy link
Author

wcarhart commented Mar 8, 2022

I think I found the issue: the schema for Profile.awards[0] has a field called issueDate, not date, so it was a typo on my end. However, I don't think this error message did a great job at illuminating where the issue was?

@IslandRhythms IslandRhythms added the help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary label Mar 9, 2022
@vkarpov15 vkarpov15 added this to the 6.2.8 milestone Mar 11, 2022
@vkarpov15 vkarpov15 modified the milestones: 6.2.9, 6.2.12 Mar 23, 2022
@vkarpov15
Copy link
Collaborator

You're right that this error message isn't great. The "string" part is a mistake that we'll fix. Digging out the root cause for this error would involve either spotting the "date" property in the string description, or drilling down into the fact that the error for awards.0 has a reason property that contains a StrictModeError.

@vkarpov15 vkarpov15 added enhancement This issue is a user-facing general improvement that doesn't fix a bug or add a new feature and removed help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary labels Apr 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement This issue is a user-facing general improvement that doesn't fix a bug or add a new feature
Projects
None yet
Development

No branches or pull requests

3 participants