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

Subdocument validation error - Cast to Array failed for value - .save() #8472

Closed
GregoryNEUT opened this issue Jan 3, 2020 · 3 comments
Closed
Labels
can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity.

Comments

@GregoryNEUT
Copy link

GregoryNEUT commented Jan 3, 2020

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

bug

What is the current behavior?

Cannot .save() changes made on a document due to validation error.

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

I have the following schema :

 {
        // Name of the language
        name: new Schema({
          description: {
            type: String,
          },

          translations: [
            new Schema({
              idLanguage: {
                type: Schema.Types.ObjectId,
                ref: 'Language',
              },

              value: {
                type: String,
              },
            }),
          ],
        }),

        // Acronym that define the language (Ex: FR, EN, ...)
        acronym: {
          type: String,
          required: true,
        },
},

I'm getting a document from the database using a .find() request, then push new data into the name.translations array and .save().

I got the following runtime error :

{
stringError: { ValidationError: Language validation failed: name.translations: Cast to Array failed for value "[ { idLanguage: 'aaaaa0000000000000000000', value: 'Français' } ]" at path "translations", name: Validation failed: translations: Cast to Array failed for value "[ { idLanguage: 'aaaaa0000000000000000000', value: 'Français' } ]" at path "translations"
at ValidationError.inspect (/home/X/back/node_modules/@cotep/database/node_modules/mongoose/lib/error/validation.js:61:24)
at formatValue (util.js:399:38)
at formatProperty (util.js:800:11)
at formatObject (util.js:616:17)
at formatValue (util.js:578:18)
at inspect (util.js:293:10)
at format (util.js:222:18)
at Console.log (console.js:130:21)
at PromiseCommandPattern.error (/home/X/back/compiled/src/DBClasses/AHaveWordCollection.js:503:19)
at PromiseCommandPattern.executeFunctionToExecute$ (/home/X/back/compiled/src/FunctionsDefinitions/PromiseCommandPattern.js:380:57)
at tryCatch (/home/X/back/node_modules/regenerator-runtime/runtime.js:45:40)
at Generator.invoke [as _invoke] (/home/X/back/node_modules/regenerator-runtime/runtime.js:271:22)
at Generator.prototype.(anonymous function) [as throw] (/home/X/back/node_modules/regenerator-runtime/runtime.js:97:21)
at tryCatch (/home/X/back/node_modules/regenerator-runtime/runtime.js:45:40)
at invoke (/home/X/back/node_modules/regenerator-runtime/runtime.js:135:20)
at /home/X/back/node_modules/regenerator-runtime/runtime.js:147:13
at
at process._tickCallback (internal/process/next_tick.js:189:7)
errors: { 'name.translations': [Object], name: [Object] },
_message: 'Language validation failed',
name: 'ValidationError' }

I've printed the data I'm trying to save :

{
     "_id": "aaaaa0000000000000000000",
     "name": {
          "_id": "5e0f30f2c38f2b59775d9bb3",
          "translations": [
               {
                    "idLanguage": "aaaaa0000000000000000000",
                    "value": "Français"
               }
          ],
          "description": "French"
     },
     "acronym": "FR",
     "__v": 0
}

It should work.

PS: The exact same code worked in previous version of mongoose 5.6.x

What is the expected behavior?

The document get successfully saved

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

node.js v8.16.2
mongodb v4.2.1
mongoose v5.8.4 (also tried with v5.7.0)

@GregoryNEUT
Copy link
Author

GregoryNEUT commented Jan 3, 2020

[WORKAROUND]

I have changed the schema to :

{
       // Name of the language
       name: new Schema({
         description: {
           type: String,
         },

         translations: [  Schema.Types.Mixed  ],
       }),

       // Acronym that define the language (Ex: FR, EN, ...)
       acronym: {
         type: String,
         required: true,
       },
},

And it worked (with the same data).

Here is the final data on the database :

image

@vkarpov15 vkarpov15 added this to the 5.8.5 milestone Jan 4, 2020
@vkarpov15
Copy link
Collaborator

The below script succeeds without throwing any errors, please modify the below script to demonstrate your issue.

'use strict';
  
const mongoose = require('mongoose');

mongoose.set('useFindAndModify', false);

const { Schema } = mongoose;

run().catch(err => console.log(err));

async function run() {
  await mongoose.connect('mongodb://localhost:27017/test', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });

  await mongoose.connection.dropDatabase();

  const schema = Schema({
    name: Schema({
      description: String,
      translations: [Schema({
        idLanguage: {
          type: Schema.Types.ObjectId,
          ref: 'Language',
        },
        value: String
      })]
    })
  });

  const Model = mongoose.model('Test', schema);

  await Model.create({ name: { description: 'Test' } });

  const doc = await Model.findOne();
  doc.name.translations.push({
    "idLanguage": "aaaaa0000000000000000000",
    "value": "Français"
  });

  await doc.save();

  console.log('Done');
}

Also, it looks like you're using some sort of transpiler, can you please clarify what transpiler you're using?

@vkarpov15 vkarpov15 added the can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity. label Jan 4, 2020
@vkarpov15 vkarpov15 removed this from the 5.8.5 milestone Jan 4, 2020
@GregoryNEUT
Copy link
Author

@vkarpov15

First, you are right I'm using a transpiler: Babel for my main project and typescript for a small package I use to interact with the database (schema handler).

I've made a lot of different try and I have state that :

  • The code you have provided me works in my project
  • I can make my code work using Schema.Type.Mixed
  • I can make my code work if I build the entire Schema in the main project (in opposition with building the Schema in my lower level package)

My conclusion :

It's 100% a transpiler issue, I got no issue when I perform every mongoose action at the same location.

Thank you for your help, I think this issue is VERY specific. Indeed my main project is migrating to typescript so I am using babel, when my lower packages are already in typescript (compilation target setted to es5).

I'll set my Schema to Schema.Type.Mixed until I finish the migration of my whole project into typescript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity.
Projects
None yet
Development

No branches or pull requests

2 participants