在MongooseError.CastError处连接500错误

时间:2015-08-22 19:14:50

标签: json angularjs node.js mongodb mongoose

这是交易:我在AngularJS / Node.JS中有一个表单,它从MongoDB中提取表单问题并为每个答案分配值。我昨晚杀了我的MongoDB数据库。幸运的是,我仍然可以使用JSON文件。使用JSON文件创建了两个新集合(与以前的数据库相同的名称),但是现在我在尝试完成表单并将数据发回到数据库对象时使用名为answers的数组时出现此错误:

Error
     at MongooseError.CastError ((HIDDEN)/node_modules/mongoose/lib/error/cast.js:18:16)
     at ObjectId.cast ((HIDDEN)/node_modules/mongoose/lib/schema/objectid.js:134:13)
     at Array.MongooseArray.mixin._cast ((HIDDEN)/node_modules/mongoose/lib/types/array.js:117:32)
     at Array.MongooseArray.mixin._mapCast ((HIDDEN)/node_modules/mongoose/lib/types/array.js:278:17)
     at Object.map (native)
     at Array.MongooseArray.mixin.push ((HIDDEN)/node_modules/mongoose/lib/types/array.js:291:25)
     at (HIDDEN)/controllers/user.js:236:22
     at (HIDDEN)/node_modules/async/lib/async.js:187:20
     at (HIDDEN)/node_modules/async/lib/async.js:239:13
     at _arrayEach ((HIDDEN)/node_modules/async/lib/async.js:91:13)
     at _each ((HIDDEN)/node_modules/async/lib/async.js:82:13)
     at Object.async.forEachOf.async.eachOf ((HIDDEN)/node_modules/async/lib/async.js:238:9)
     at Object.async.forEach.async.each ((HIDDEN)/node_modules/async/lib/async.js:215:22)
     at exports.postWizard ((HIDDEN)/controllers/user.js:233:11)
     at Layer.handle [as handle_request] ((HIDDEN)/node_modules/express/lib/router/layer.js:95:5)
     at next ((HIDDEN)/node_modules/express/lib/router/route.js:131:13)
POST /wizard 500 234.552 ms - -

1 个答案:

答案 0 :(得分:0)

通过为嵌套对象生成ID来解决此问题。我不得不插入每个文件的db。 MongoDB不会自动为嵌套对象生成ID;因此,我不得不使用ObjectId():

 db.questions.insert({ 
    "question": "q1",
    "order": 1,
    "type": "assessment",
    "answers": [{
        "_id" : ObjectId(),
        "answer": "Yes",
        "value": 1
    }, {
        "_id" : ObjectId(),
        "answer": "No",
        "value": 0
 }]})