skip to Main Content

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.

2

Answers


  1. You could use $push

     User.updateOne({_id: userId}, { $push: { vitalSigns: data } })
    
    Login or Signup to reply.
  2. Use $ to access the array element matched.

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

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search