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

193
Visualizações
Argument passed in must be a string of 12 bytes

Hello guys i'm getting this message when i'm trying to delete an entry in my DB. I have tried JSON.parse on the req.body,switched the routes in my routes file yet nothing seems to work.

this is my controller :

async function removeToy(req, res) {
  try {
    const { toyId } = req.params
    const removedId = await toyService.remove(toyId)
    res.send(removedId)
  } catch (err) {
    logger.error('Failed to remove toy', err)
    res.status(500).send({ err: 'Failed to remove toy' })
  }
}

this is the service :

async function remove(toyId) {

  try {
      const collection = await dbService.getCollection('toy')
      await collection.deleteOne({ '_id': ObjectId(toyId)})
      return toyId
  } catch (err) {
      logger.error(`cannot remove toy ${toyId}`, err)
      throw err
  }
}

also added a picture of how the DB looks like: enter image description here

and the picture of the entire error : enter image description here

appreciating any kind of help!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In your database you have an object whose _id is of type string.

In your query, you're casting (presumably) a string to an ObjectID, which is an object. Not only is the argument you're passing to ObjectId() not something that it supports (as the error indicates, see below), even if it would be valid, the query would result in 0 hits: after all "TZ23c" !== ObjectId("TZ23c").

Simply change .deleteOne({_id: ObjectId(toyId)}) to .deleteOne({_id: toyId}).

ObjectId() either takes no argument (it will return a new value) or it takes exactly 12 bytes (24 hexadecimal characters), for example: ObjectId("61e16f21f82a9db6a2094e78").

An ObjectId's string representation (ObjectId().toString()) is not an arbitrary string of characters: it's a timestamp, some values that identify which server generated it and some random values to prevent collisions. Not every string is a valid ObjectId.

about 4 years ago · Juan Pablo Isaza Relatório

0

As the message suggest your toyId passed to the function is with wrong lenght , it must be 12 bytes long , example:

  mongos> ObjectId("x448c")
  2022-01-14T13:43:51.427+0100 E QUERY    [js] Error: invalid object id: length 
  :
  @(shell):1:1
  mongos>

The correct is:

  mongos> ObjectId("61e16facafe3aa6023c221bb")
  ObjectId("61e16facafe3aa6023c221bb")
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