这是我的收藏结构的概述:
{
profile: {
first_name: 'Plop',
surname: 'Plopette',
...
},
medical_history: {
significant_illnesses: [
'Asthma',
'Diabetes'
],
...
}
}
如何访问和更新 medical_history.significant_illnesses
数组中的一项?
我所拥有的是惨败:
Patients.update(Session.get("current_patient"), {
$push: {
"medical_history.significant_surgeries.surgeryIndex": $(event.target).val().trim()
}
});
注意,surgeryIndex
是动态的,因此我无法对任何内容进行硬编码。
上面的更新代码会产生此错误:
Exception while simulating the effect of invoking '/patients/update'
errorClass {
error: 409,
reason: "MinimongoError: can't append to array using string field name [surgeryIndex]",
details: undefined, message: "MinimongoError: can't append to array using string field name [surgeryIndex] [409]",
errorType: "Meteor.Error"}
最佳答案
最好的方法是取出数组,修改它并使用 $set
查询更新回来。
如果你真的想按照自己想要的方式去做,你需要 $pull数组中的值,然后您必须使用 $position 将其推送到特定索引运算符。
但是 $position
运算符是在 2.6 版本中引入的。如果您使用的版本比该版本更旧,据我所知,除了我的第一个建议之外,您没有其他选择。
关于mongodb - meteor /MongoDB : Update an array item in a collection by index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38862847/