2016-05-06 6 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); 
          } 
         } 
        } 
       ); 
      } 
     } 
    }); 
} 

スキーマ:

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

答えて

0

あなたのコードは、あなたがデータを更新したいときだけDoctorModelfoundDataを変更、ほぼ正しいです私はaddOrUpdateAppointment()に渡しています

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

データ、 。コードは次のようになります。

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