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

171
Visualizações
How to update only if my object has a certain field

I have a mongo db document like this

id: ObjectId(asdlkjjas_48@$#),
_user: 4593oawifjaslef,
country: { US: false, CA: false, MX: false, FR: false }
name: "kevin"
age: 28

I am getting a post request from the frontend with the objectId (needed to query for this document) and also a country code

So my user sends their Id and countryCode to backend, I need to update the document that matches that id, and only update the countryCode that is nested in country.

I tries something like this

incomingNumber = await Collection.findById(numberId) // get our document by id
const code = 'US' // get our country code
collection.updateOne({_id: incomingNumber}, {$set: { country[code]: true }}) //trying to update only the field in country(object) that matches our supplied country code(ex. 'US')
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Someone posted the answer for a few seconds then deleted, repost your answer and i will give you credit.

The answer is to

Collection.updateOne({_id: incomingNumber}, {$set: { country: { [code]: true}}})

I basically needed an extra curly brace. This does work for me in this situation, however The country object will now look like this

{ US: true },

I would rather have

 { US: true, FR: false, MX: false, CA: false }
about 4 years ago · Juan Pablo Isaza Relatório

0

Inorder to preserve the country object and retain the keys that are not updated, you can either use template literals since its mongoose or use square-brackets,

Collection.updateOne({_id: objectId}, {$set: { ["country."+code]: true}})

or

Collection.updateOne({_id: objectId}, {$set: { `country.${code}`: true}})
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