Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
Cast to ObjectId failed for value (type Object) at path "_id" for model "User" in mongoDB

Am trying to use the userId from the Params to fetch that particular user friends.

    router.get("/friends/:userId", async (req, res) => {
    try {
    const user = await User.findById({userId:req.params.userId});
    const friends = await Promise.all(
      user.following.map((friendId) => {
        return User.findById(friendId);
      })
     );
    let friendList = [];
    friends.map((friend) => {
      const { _id, username, profilePicture } = friend;
      friendList.push({ _id, username, profilePicture });
    });
    res.status(200).json(friendList)
    console.log(friendList)
    } catch (err) {
    res.status(500).json(err);
    console.log(err)
    }
    });

But I get this error

    CastError: Cast to ObjectId failed for value "{ userId: '61543261597a97bfdf670f0b' }" (type Object) at path "_id" for model "User"

friends data in my when I Log it out to see...

    [
    undefined,
    {
    _id: new ObjectId("6154346027ecc696433f5b86"),
    username: 'Hemmyhtec',
    email: 'emmmmaee@gmail.com',
    password: '$2b$10$wVkZGu4PxlmW3geXfeBwHOxGeK6v7wyjyV7xeLzBNWQSeg5LtA.eW',
    profilePicture: 'logo3.jpg',
    coverPicture: '',
    followers: [ '', '61543261597a97bfdf670f0b' ],
    following: [ '' ],
    isAdmin: false,
    createdAt: 2021-09-29T09:39:44.199Z,
    updatedAt: 2021-10-02T20:25:38.569Z,
    __v: 0
   }
   ]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

When you use findById(), your should pass only the value of the _id and not the object userId with that value. Change your code like this:

const user = await User.findById(req.params.userId);
about 4 years ago · Juan Pablo Isaza Relatório

0

Replace this

user.following.map((friendId) => {
return User.findById(friendId);

})

with

user.following.map((friendId) => {
if(!friendId) return
return User.findById(friendId);

})

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda