Mongoose: TypeError: Cannot read property 'length' of undefined

Created on 25 Oct 2016  路  5Comments  路  Source: Automattic/mongoose

When using versions 4.6.4 and 4.6.5:

\node_modules\mongoose\lib\index.js:445
  for (i = 0, len = schema.childSchemas.length; i < len; ++i) {
TypeError: Cannot read property 'length' of undefined

No error when using versions 4.6.3 and lower.

Most helpful comment

Got the same issue but it was due to a mistake in my code. ie:

Before:

var List = mongoose.model('List', ListSchema);
List.createMapping(..);
module.exports = mongoose.model('List', List);

After:

var List = mongoose.model('List', ListSchema);
List.createMapping(..);
module.exports = List;

All 5 comments

Code sample please

Got the same issue but it was due to a mistake in my code. ie:

Before:

var List = mongoose.model('List', ListSchema);
List.createMapping(..);
module.exports = mongoose.model('List', List);

After:

var List = mongoose.model('List', ListSchema);
List.createMapping(..);
module.exports = List;

Thanks @Alexandre-io, I'll check it out.
@vkarpov15 I'll try to isolate the issue, sorry about the blurry description.
(I assumed it's a large scale issue and not something specific to my code)

I did a similar upgrade that @ronenteva did and hit the same error. The existing problem in my code was very similar to what @Alexandre-io described.

I also edited the mongoose/lib/index.js file and on line 445, as per the snippet that @ronenteva pasted, I changed schema.childSchemas.length to (schema.childSchemas || []).length which fixes the problem.

@vkarpov15 I'm not sure if you want users to come and find this issue and then work out how their code is incorrect and fix it with clues from here, or if you want to add a temporary fix as I've just described and then deprecate that temporary fix as a breaking change in the next major release of mongoose?

Based on what @Alexandre-io described, this is just a case of "garbage in, garbage out". 2nd parameter to .model() should be a schema or a POJO that you can pass to the schema constructor. If it isn't, you're gonna have a bad time. In the next release, we'll throw a more informative error in that case.

Was this page helpful?
0 / 5 - 0 ratings