[Mongoose] TypeError: Cannot read property ‘options’ of undefined
Mongoose でスキーマ定義に type: ObjectId としている field にオブジェクト型のデータが入ってると TypeError: Cannot read property ‘options’ of undefined エラーが発生します。
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.<anonymous> (/u/apps/com/shared/node_modules/mongoose/lib/query.js:1160:11) at Promise.<anonymous> (/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) |
再現手順ですが、例えば下記のようなスキーマ定義で、
Article = new Schema user: type: ObjectId ref: 'User' |
user filed に ObjectId ではなく { name : ‘hoge’ } のような値を入れて、save するとエラーが発生します。
article = new Article article.user = { name : 'hoge' } // ObjectId じゃない! article.save()-> |
findAndModify などの Mongo DB Native NodeJS Driver を直接呼ぶメソッド findOneAndUpdate メソッドを使ったり、mongo shell で直接データを編集したりするとこういうエンバグさせてしまうので、必要ない限りやめたいですね。