Home > Blockchain >  How to update only if my object has a certain field
How to update only if my object has a certain field

Time:10-27

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')

CodePudding user response:

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 }

CodePudding user response:

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}})
  • Related