1
votes

I'm working on a backend, and I have this route that is supposed to return just an array of ID's from the database for later lazy loading. My route is defined like this:

 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));
 });

which should return an array like this [_id, _id, _id....]

But I am getting a very weird error:

Cast to ObjectId failed for value "list" at path "_id" for model "insiders" CastError: Cast to ObjectId failed for value "list" at path "_id" for model "insiders" at new CastError (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\error\cast.js:27:11) at ObjectId.cast (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\schema\objectid.js:158:13) at ObjectId.SchemaType.applySetters (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\schematype.js:724:12) at ObjectId.SchemaType._castForQuery (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\schematype.js:1113:15) at ObjectId.SchemaType.castForQuery (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\schematype.js:1103:15) at ObjectId.SchemaType.castForQueryWrapper (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\schematype.js:1082:15) at cast (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\cast.js:300:32) at model.Query.Query.cast (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\query.js:3309:12) at model.Query.Query._castConditions (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\query.js:1293:10) at model.Query.Query._findOne (C:\Users\rutherfordc\Documents\GitHub\ccs-express-mongo\node_modules\mongoose\lib\query.js:1518:8) at 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)

I've confirmed that it is actually the route name that is leaking into my route handler. (i.e. I changed the route to /jerry for S&G, and "list" was replaced with "jerry" in the error)

2

2 Answers

0
votes

I think the problem is in your find method try to change it to like this

 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));
});

I think you should use id instead of _id and set its value to 0

0
votes

Turned out this was a route priority issue. there was a /:insiderId route before the /list route.

apologies.