2

This is an overview of the structure of my collection:

{
  profile: {
    first_name: 'Plop',
    surname: 'Plopette',
    ...
  },
  medical_history: {
    significant_illnesses: [
      'Asthma',
      'Diabetes'
    ],
    ...
  }
}

How do I access and update one of the items in the medical_history.significant_illnesses array?

What I have is failing miserably:

Patients.update(Session.get("current_patient"), {
    $push: {
        "medical_history.significant_surgeries.surgeryIndex": $(event.target).val().trim()
    }
});

Note, surgeryIndex is dynamic so I can't hard-code anything.

The update code above produces this error:

Exception while simulating the effect of invoking '/patients/update'

errorClass {
    error: 409,
    reason: "MinimongoError: can't append to array using string field name [surgeryIndex]",
    details: undefined, message: "MinimongoError: can't append to array using string field name [surgeryIndex] [409]",
    errorType: "Meteor.Error"}
wiredfordesign
  • 211
  • 3
  • 11
  • What exactly you are trying to do? Have you read any doc about `$push` before using it? If not then please refer [doc](https://docs.mongodb.com/manual/reference/operator/update/push/#examples) . – Shrabanee Aug 10 '16 at 04:58
  • 2
    Can you show more of your document, specifically the `significant_surgeries` key that you are trying to change? `$push` appends an element to an array. If you want to change an element it needs to be specified in the selector as well. – Michel Floyd Aug 10 '16 at 05:10

1 Answers1

3

Best way is to take the array out, modify it and update it back with $set query.

If you really want to do the way you want, you need to $pull the value from the array and then you have to push it to specific index using $position operator.

But $position operator introduced in version 2.6. In case if you are using older than that, as far as i know you don't have any other choice than my first suggestion.

user10
  • 5,186
  • 8
  • 43
  • 64