Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!