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
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 :
You have a
Human.id
andHuman.person.id
property in your schema but your database documents show aHuman.humanID
andHuman.person.humanAdultId
. These need to have the same key, eitherid
orhumanID
andhumanAdultId
.Assuming your schema should be
humanID
andhumanAdultId
then based on your schema theHuman.humanID
and theHuman.person.humanAdultId
values are both of typeString
. As such you can find theHuman
that matches thejsonData.humanID
and pick out the object from theperson
array that has aperson.humanAdultId
equal tojsonData.person.humanAdultId
like so: