我正在尝试向治疗阵列中添加一个新项目。它基本上是存储特定医院提供的程序列表。医院ID是医院的唯一ID,它由后api创建随着该医院提供的治疗清单。当医院引入新的外科手术时,我需要将其添加到治疗阵列中,因为我已经创建了一个put API
每当我在API中调用以下代码段时,我都会收到以下错误
The positional operator did not find the match needed from the query. Unexpanded update: Treatment.$.procedureid
请帮我解决一下。
您可以在下面找到型号和控制器代码:
var hospitalDoctorSchema = new Schema({
hospitalID: { type: Number, required: true, unique: true, dropDups: true, default: 10000 },
Treatment: [{
procedureid: { type: Number},
departmentId: { type: Number},
name: { type: String, required: true, trim: true },
costUpperBound: { type: Number, required: true },
costLowerBound: { type: Number, required: true },
departmentName: { type: String, required: true, trim: true},
}],
updated_at: { type: Date, required: true, default: Date.now }
});
hospitalModel.findOneAndUpdate({ "hospitalID": 10000}, { "$set": {"Treatment.$.procedureid"=1100}, { returnOriginal: false, upsert: true }, function (err, doc) {
if (err) {
logger.error("Error while updating record : - " + err.message);
return res.status(500).json({ "Message": err.message });
} else if (doc === null) {
logger.error("Error while updating record : - Hospital not found in database");
return res.status(408).json({ "Message": "Hospital not found in database" });
}
res.status(200).json({ "Message": "Hopsital details for " + hospitalName + " have been updated successfully" });
});
答案 0 :(得分:0)
如果要在数组中添加新元素。您必须使用 $ push 而不是 $ set 。因为 $ push 用于插入元素,而 $ set 仅用于更新。 所以
hospitalModel.findOneAndUpdate({ "hospitalID": 10000},{"$push":
{"Treatment" : { "procedureid" : 1100 } } }, { returnOriginal: false,
upsert: true }, function (err, doc) { ... });