3

So I have a db model defined in my server.js file which will be used for a POST :

var department = mongoose.model('department', {
  departmentName: String,
  rooms: [{
    roomNumber: String,
    width: Number,
    height: Number,
    posX: Number,
    posY: Number,
    sanitary: Boolean,
    childcareArea: Boolean,
    lounge: Boolean,
    patient: {
      patientnr: Number,
      firstname: String,
      lastname: String,
      reasonOfHospitalization: String,
      dateOfHospitalization: String,
      expectedDateOfDischarge: String,
      vegetarian: Boolean,
      needsHelp: Boolean,
      comments: String,
      department: String,
      roomNumber: String,
      nextTreatment: {
        type: String,
        shortDescription: String,
        timestamp: String
      }
    }
  }]
});

Now what I want to achieve is that my post call updates the patient object.

 public postPatient(patient: Patient) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=utf-/8');

    let url ='http://localhost:8080/api/departments/patients/' + patient.patientnr;

    this.http.post(url, JSON.stringify(patient), headers)
      .map(res => res.json());
  }

This is how I handle my post, but it updates nothing in my database...

app.post('/api/departments/patients/:id', function(req, res) {
  var patient = req.body.patient;

  department.findOneAndUpdate(
    { "rooms.patient.patientnr": parseInt(req.params.id) },
    {
      "rooms": {
        "$elemMatch": {
          "patient.patientnr": parseInt(req.params.id)
        }
      }
    }, {
      "$set": {
        "rooms.patient": patient
      }
    }, {
     new : true
    },
    function (err, dept) {
      if (err){
        console.log(err.stack);
        return res.send(err);
      }
      return res.json({
        data: department,
        status: 'success'
      });
    });
});

1 Answer 1

1

Something like this should work for you. Finds and replace the patient for the selected room.

department.findOneAndUpdate(
    { "rooms.patient.patientnr": parseInt(req.params.id) },
    { "$set": {"rooms.$.patient": patient}},
    {new : true}
    ....
)
Sign up to request clarification or add additional context in comments.

3 Comments

thanks :) I only get an error saying that my timestamp can't convert to a string but I'll fix that.
really appreciate your help!
Do you know why I get this error: MongooseError: Cast to string failed for value "{ timestamp: '2017-01-12T05:09', Only fault left...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.