【发布时间】:2016-09-01 06:40:54
【问题描述】:
我正在尝试使用以下代码更新数组中的 json 对象。该代码似乎在数组中找到 json 对象,但是,它无法更新 json 数组中的 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"
}
}
【问题讨论】:
标签: json node.js mongodb mongoose