首页 > 解决方案 > MongooseJS 奇数转换错误,路由名称出错

问题描述

我正在处理后端,我有这条路线应该只从数据库中返回一个 ID 数组,以便以后延迟加载。我的路线是这样定义的:

 router.get('/list', (req, res) => {
   Insider.find({}, {_id}).then(insiders => {
     if (!insiders) {
       res.status(400).json({ error: 'unable to find list of insiders' });
     }
     res.json(insiders);
   }).catch(err => res.status(400).json(err));
 });

它应该返回一个这样的数组[_id, _id, _id....]

但我收到一个非常奇怪的错误:

模型“内部人员”CastError 的路径“_id”中的值“列表”转换为 ObjectId 失败:新 CastError 中模型“内部人员”的路径“_id”中的值“列表”转换为 ObjectId 失败(C:\Users\rutherfordc \Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\error\cast.js:27:11) 在 ObjectId.cast (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules \mongoose\lib\schema\objectid.js:158:13) 在 ObjectId.SchemaType.applySetters (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\schematype.js:724 :12) 在 ObjectId.SchemaType._castForQuery (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\schematype.js:1113:15) 在 ObjectId.SchemaType.castForQuery (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\schematype.js:1103:15) 在 ObjectId.SchemaType.castForQueryWrapper (C:\Users\rutherfordc\Documents\GitHub\ccs-express -mongo\node_modules\mongoose\lib\schematype.js:1082:15) 在演员表 (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\cast.js:300:32 ) 在 model.Query.Query.cast (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\query.js:3309:12) 在 model.Query.Query._castConditions ( C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\query.js:1293:10) 在 model.Query.Query._findOne (C:\Users\rutherfordc\Documents\GitHub \ccs-express-mongo\node_modules\mongoose\lib\query.js:1518:8) 在 process.nextTick (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\kareem\index.js:333:33) at _combinedTickCallback (internal/process/next_tick.js:131:7) at process._tickCallback (internal/process /next_tick.js:180:9)

我已经确认它实际上是泄漏到我的路由处理程序中的路由名称。(即我将路由更改/jerry为S&G,错误中的“list”被替换为“jerry”)

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


我认为问题在于您的find方法尝试将其更改为这样

 router.get('/list', (req, res) => {
 Insider.find({}, {id:0}).then(insiders => {
  if (!insiders) {
   res.status(400).json({ error: 'unable to find list of insiders' });
   }
     res.json(insiders);
  }).catch(err => res.status(400).json(err));
});

我认为您应该使用 id 而不是 _id 并将其值设置为 0


推荐阅读