ValidationError when using array in Schema
See original GitHub issueDo you want to request a feature or report a bug? Report a bug
What is the current behavior? After defining my schema similar to the following one:
const UserSchema = new mongoose.Schema({
roles: {
type: [String],
index: true,
},
});
mongoose.model('User', UserSchema)
If I try to instantiate a new User like this:
const user = new User({ roles: ['super-admin'] });
It raises the following exception ValidationError: User validation failed: roles: Cast to Array failed for value "[ 'super-admin' ]" at path "roles"
Instantiating the user with an empty roles
array does not raise any exception.
This is happening on mongoose@5.6.9, downgrading to 5.6.8 fixes it.
If the current behavior is a bug, please provide the steps to reproduce.
The schema shown above should be enough to reproduce the issue.
What is the expected behavior?
No ValidationError
exception raised when instantiating a model with an array in the schema.
What are the versions of Node.js, Mongoose and MongoDB you are using? Note that “latest” is not a version. node 10.16.0 mongoose 5.6.9 mongo 4.0.4
Issue Analytics
- State:
- Created 4 years ago
- Reactions:15
- Comments:13 (1 by maintainers)
@vkarpov15 I have put together a small reproduction repository: https://github.com/BrunoGodefroy/repro-mongoose-issue-8053
I tried to simplify it at a maximum to showcase the error, I could not remove jest while keeping the bug so it might be caused by babel transpiling the code for jest.
Hope that helps
This appears to be yet another bug with Jest. Not to harp about this too much, but Jest is horribly broken and you should really use Mocha or some other framework that doesn’t invent its own JavaScript runtime that isn’t quite Node.js or a browser. Because Jest makes up its own runtime by monkeypatching everything, code that works fine in Node.js may not work in Jest and vice versa, so Jest is not a reliable way to test Node.js projects.
It looks like this issue comes down to Jest stubbing out
require()
, so if yourequire('./)
in a directory where the parent dir happens to have a file with the same name as the current directory, Jest’srequire()
gives you the parent dir’s file. For example, suppose you have the below file structure:test.js
dir.js
dir/index.js
dir/fn.js
Running
test.js
will output:As opposed to
nested
like in Node.js.