Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda