skip to Main Content

This is my mongoose schema:

const humanSchema = mongoose.Schema({
    id: String,
    person: [
        id: String,
        age: Number,
        sex: String,
        height: String
    ],
    employment: Boolean
});

This is my JSON body request I am trying to pass through postman as a PUT:

"humanID": "12345"
"personUpdate": {
  "humanAdultId": "6789",
  "age": 37,
  "sex": "male",
  "height": "5ft"
}

This is my ‘human’ database record that I am trying to update:

"id": "12345"
"person": [
{
  "id": "4321",
  "age": 21,
  "sex": "female",
  "height": "4ft"
},
{
  "id": "6789",
  "age": 35,
  "sex": "male",
  "height": "6ft"
},
{
  "id": "7654",
  "age": 27,
  "sex": "male",
  "height": "5ft"
}
]

I am trying to use the JSON body to update the 2nd object in the array. I want to update its values: age and height.

I want to do this by calling the Id of the overall record (humanID) and then the object Id (humanAdultId) to drill down further to the object I need. I have researched the $pull and $push route, but there has to be an easier way to do this. What would be the best way to accomplish this?

2

Answers


  1. you should use a simple update with an arrayFilters !

    See the documentation here for details : https://www.mongodb.com/docs/v7.0/reference/method/db.collection.update/#specify-arrayfilters-for-array-update-operations

    Something as follow should work :

    humanCollection.findOneAndUpdate(
      {_id : myJson.humanId},
      {$set : {"person.$[myHumanAdult]" : myJson.person},
      {arrayFilters : [{"myHumanAdult.humanAdultId" : myJson.person.humanAdultId}]}
    )
    
    Login or Signup to reply.
  2. You have a Human.id and Human.person.id property in your schema but your database documents show a Human.humanID and Human.person.humanAdultId. These need to have the same key, either id or humanID and humanAdultId.

    Assuming your schema should be humanID and humanAdultId then based on your schema the Human.humanID and the Human.person.humanAdultId values are both of type String. As such you can find the Human that matches the jsonData.humanID and pick out the object from the person array that has a person.humanAdultId equal to jsonData.person.humanAdultId like so:

    const human = await Human.findOneAndUpdate(
    {
       humanID: jsonData.humanID,
       person: {
           $elemMatch: {
              humanAdultId: jsonData.person.humanAdultId,
           }
       } 
    },
    {
       $set : {
          "person.$" : jsonData.person
       }
    },
    {new: true}
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search