1

I am getting this error:

UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "get-votes at path "_id" for model "Data"

This is my model:

const dataSchema = new Schema({
  username: { type: String, required: true },
  votes: Number,
});

This is my route:

router.get('/most-votes', (req, res, next) => {
  return Data.find({}, function(error, data) {
    let dataMap = {};

    data.forEach(e => dataMap[data._id] = e);
    res.send(dataMap);
  });
});

However, I still get the above message. Can someone help please?

EDIT: I have checked the above "possible duplicate", however, it is not duplicate. I am using .find().

strong tu
  • 21
  • 4
  • 1
    The code you are posting is not the problem. Presumably you have a different route which actually has a `findById()` method in it. Possibly `/post/:id` or `/user/:id` or whatever the "master" route here is and you thought you have a `/post/get-votes` ( or whatever ) route, but that is being passed in as a `param` value. So the error is most likely where a `findById()` is in the code, but the cause is route params. – Neil Lunn Mar 07 '19 at 08:33
  • But I do have a `get-votes` route as well, which is a separate one. – strong tu Mar 07 '19 at 08:40
  • You "think" you have a separate route, but that route is not being hit because it's passing into the "parameters" of the root on that controller path. Add a `console.log('hi')` in the route you think is being hit and see that it is not. You are hitting the one with the `findById` in it. – Neil Lunn Mar 07 '19 at 08:42
  • I see, so what should I do? Can you please write answer, I will gladly accept it. Thanks man. – strong tu Mar 07 '19 at 08:46
  • The linked answers ( and I just added something more directly related to your problem ) have about the same information I have given and should guide you. Besides you did not even post the code for the route which is actually causing the problem. – Neil Lunn Mar 07 '19 at 08:51
  • Ok, will check more, thanks. – strong tu Mar 07 '19 at 08:55

0 Answers0