[Mongoose] TypeError: Cannot read property 'options' of undefined
In Mongoose, when object-type data is in a field defined as type: ObjectId in the schema definition, a “TypeError: Cannot read property ‘options’ of undefined” error occurs.
TypeError: Cannot read property 'options' of undefined
at ObjectId.cast (/u/apps/com/shared/node_modules/mongoose/lib/schema/objectid.js:99:22)
at /u/apps/com/shared/node_modules/mongoose/lib/document.js:288:29
at model.Document.$__try (/u/apps/com/shared/node_modules/mongoose/lib/document.js:769:8)
at init (/u/apps/com/shared/node_modules/mongoose/lib/document.js:287:16)
at model.Document.init (/u/apps/com/shared/node_modules/mongoose/lib/document.js:246:3)
at completeOne (/u/apps/com/shared/node_modules/mongoose/lib/query.js:1392:10)
at Promise. (/u/apps/com/shared/node_modules/mongoose/lib/query.js:1160:11)
at Promise. (/u/apps/com/shared/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
at Promise.EventEmitter.emit (events.js:95:17)
at Promise.emit (/u/apps/com/shared/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
at Promise.fulfill (/u/apps/com/shared/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)
at Promise.resolve (/u/apps/com/shared/node_modules/mongoose/lib/promise.js:114:23)
at /u/apps/com/shared/node_modules/mongoose/lib/model.js:2029:23
at process._tickCallback (node.js:415:13)
To reproduce this, for example, with a schema definition like this:
Article = new Schema
user:
type: ObjectId
ref: 'User'
An error occurs when you put a value like { name : ‘hoge’ } instead of ObjectId in the user field and save.
article = new Article
article.user = { name : 'hoge' } // Not an ObjectId!
article.save()->
Since this kind of bug can occur when using methods like findOneAndUpdate that directly call MongoDB Native NodeJS Driver methods like findAndModify, or when editing data directly in the mongo shell, it’s best to avoid these unless necessary.
That’s all from the Gemba.