0

Ive been trying these since yesterday but I couldnt make it.

I have 2 different Schemas, the User Schema and the Vital Signs Schema. The Vital Signs Schema is inside the userSchema as an array. What i need to do is to edit an specific vitalSigns object with an unique Id

Here is a postman example of the info i need to update

1

const userSchema = new mongoose.Schema({
    email:{type: String, required: true},
    password:[{type: String, required: true}],
    confirmPassword:[{type: String, required: true}],
    personalData: personalDataSchema,
    vitalSigns: [vitalSignsSchema],
})
const vitalSignsSchema = new mongoose.Schema({
    systolic: { type: 'Number', required: false },
    diastolic: { type: 'Number', required: false },
    temperature: { type: 'Number', required: false },
    pulse: { type: 'Number', required: false },
    rate: { type: 'Number', required: false },
    blood: { type: 'Number', required: false },
    date: { type: 'Date', required: false },
})

My route is catching both userId and vitalSigns because i tried to make it work with a lot of ways but i couldn't

Router.post('/user/:userId/vitalSignsEdit/:vitalId', async (req, res) => {
    
    userServices.editVitalSigns(req.params.userId,req.params.vitalId, req.body)


})

Here is one example of a way that I tried to use to make it work but instead of updating the specific vitalSigns Id, it created another object of vitalSigns with the same Id that i tried to change.

  User.findById(userId)
  .then( user => {
    if(user) {
      if(user.vitalSigns.find( e => e._id === data._id)) {
        User.updateOne({_id: userId}, { vitalSigns: [...user.vitalSigns, data] })
        .then(e => console.log(e), i => console.log(i))
      }
    }
  })

Hope someone could help me with these.

ray
  • 11,310
  • 7
  • 18
  • 42
  • Please [edit] to paste the text used in the image into your question so that it can be read on all devices, quoted, edited, and found through search. As it stands now, [your image makes it hard to answer your question or for people with related issues to find your question](//meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question). See the [formatting documentation](/editing-help) for tips to make your text appear nicely without resorting to images. – ray Feb 14 '23 at 15:25

2 Answers2

0

You could use $push

 User.updateOne({_id: userId}, { $push: { vitalSigns: data } })
bill.gates
  • 14,145
  • 3
  • 19
  • 47
0

Use $ to access the array element matched.

db.collection.update({
  "vitalSigns._id": "vs1"
},
{
  $set: {
    "vitalSigns.$.modified": true
  }
})

Mongo Playground

ray
  • 11,310
  • 7
  • 18
  • 42