0

I have an array in mongo document as below.

{
  company: [ 
    {name: "exist"}, 
    {name: "cool"},
    {name: "ho"}
  ]
}

And I want to get rid of a data in the array with position value.

So I made a query.

   await Company.findOneAndUpdate({
      _id: "xdef"
      },
      {
        $unset: {
           'company.1': 1
        }
      }
    })

It works very well. And now,I want to put position by query.

   await Company.findOneAndUpdate({
      _id: "xdef"
      },
      {
        $unset: {
           `company.{req.query.position}`: 1
        }
      }
    })

But it gives me an error. How can I make a code for this situation adequately?
Thank you so much for reading it.

1 Answer 1

1

You can use the computed property names. And you are missing $ also in the string literal.

 await Company.findOneAndUpdate({
    _id: "xdef"
  }, {
    $unset: {
      [`company.${req.query.position}`]: 1
    }
  }
})

With Computed Property Names you can use an expression that will be computed as a property name on an object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.