2016-05-06 78 views
0

我想使用以下代碼更新數組中的json對象。代碼似乎是在數組中找到json對象,但是,它無法更新json數組內的json對象。它不會給出任何錯誤,所以這使得它更容易混淆。如何使用Mongoose在JsonArray中獲取json對象

function addOrUpdateAppointment(jsonObject, isDatabaseOperationSuccessful) { 
    var docID = jsonObject.doctorID; // this is _id from db sent to the doctor upon logging in 
    console.log("jsonPssed: ", {_id : docID}); 
    DoctorModel.findOne({_id : docID, 'appointmentList.patientID': jsonObject.appointment.patientID}, {'appointmentList.$.patientID': jsonObject.appointment.patientID},function(err, foundData) { 
     console.log("found data", foundData); 
     if(err) { 
      console.error("error in find doctor for adding the appointment", err); 
      isDatabaseOperationSuccessful(false, foundData); 
      return; 
     } 
     else { 
      // since no document matched your query, add the appointment 
      if (!foundData) { 
       DoctorModel.update(
        {_id: docID}, 
        {$push: {appointmentList: jsonObject.appointment}}, 
        function(err, pushedData) { 
         if(err) { 
          console.error("error in adding", err); 
          isDatabaseOperationSuccessful(false, pushedData); 
         } 
         else { 
          console.log("adding successful", pushedData, "inserted: ", jsonObject.appointment); 
          isDatabaseOperationSuccessful(true, pushedData); 
         } 
        } 
       ); 
      } 
      // since that appointment already exists, update it 
      else { 
       foundData.update({'_id':docID,'doctors.appointmentList.patientID' : jsonObject.appointment.patientID}, {$set: {'doctors.appointmentList.$.dateAndTime': jsonObject.appointment.dateAndTime}}, 
        function(err, updatedData) { 
         if (err) { 
          console.error("error in updating", err); 
          isDatabaseOperationSuccessful(false, foundData); 
         } 
         else { 
          if (!updatedData) { 
           console.log("updating failed", updatedData); 
           isDatabaseOperationSuccessful(true, foundData); 
          } 
          else { 
           console.log("updating successful", updatedData); 
           isDatabaseOperationSuccessful(true, foundData); 
          } 
         } 
        } 
       ); 
      } 
     } 
    }); 
} 

模式:

doctorSchema = mongoose.Schema({ 
     name : String, 
     appointmentList : Array // array of jsonObjects of dates and time 
    }); 

數據,我傳遞給addOrUpdateAppointment(),

{ 
    "docID": "id assigned by mongoDB", 
    "appointment": { 
     "patientID": "id assigned by mongoDB", 
     "dataAndTime": "IIII" 
    } 
} 

回答

0

你的代碼幾乎是正確的只是改變foundDataDoctorModel當你想更新數據。所以代碼變爲:

  else { 
DoctorModel.update({'_id':docID, 'appointmentList.patientID' : jsonObject.appointment.patientID}, {$set: {'appointmentList.$': jsonObject.appointment}}, 
        function(err, updatedData) {....}); 
相關問題