无法更新mongoose模型 [英] Unable to update mongoose model
问题描述
我有一个令人困惑的奇怪问题。我有一个模型:
I have a weird issue that is baffling me. I have a model:
var Model = new Schema({
name: String,
variations: Array
});
变体条目如下所示:
[ {code: '', price: '' }, {code: '', price: '' }]
我需要添加一个新字段 - 比如color。所以我这样做是批量更新:
I need to add a new field - say "color". So I am doing this to batch update:
Model.find().exec(function(err, products) {
if (!err) {
products.forEach(function(p) {
for(var i = p.variations.length - 1; i >= 0; i--) {
p.variations[i]['color'] = 'red';
// This shows all existing variations
// with the new color feed - correct
console.log(p.variations[i]);
}
p.save(function(err) {
if (!err) {
console.log("Success");
} else {
console.log(err);
}
});
});
}
});
然而,颜色字段未设置 - 如果我再次检查并注释掉 p.variations [i] ['color'] ='red';
行然后它不会显示。我似乎无法弄清楚为什么这样做。我有一个正确触发的onSave事件,所以它正在保存。我也没有检查变体结构 - 即没有代码只允许代码和价格。我显然遗漏了一些东西,但几个小时后我就没想完了。
However the "color" field is not set - if I go through again and comment out the p.variations[i]['color'] = 'red';
line then it does not show. I can't seem to figure out why it's doing this. I have an onSave event that is triggered correctly so it's saving. I also do not have any check on the variations structure - i.e. there is no code that only allows code and price. I'm obviously missing something but after a couple of hours I ran out of ideas.
推荐答案
修改内容时无类型数组
字段,如变种
,您需要通过调用<$ c $通知Mongoose您已更改其值c>修改后的文档上的markModified(路径)或后续的 save()
调用将不会保存它。 查看文档。
When you modify the contents of an untyped Array
field like variations
, you need to notify Mongoose that you've changed its value by calling markModified(path)
on the modified document or a subsequent save()
call won't save it. See docs.
for(var i = p.variations.length - 1; i >=0; i--) {
p.variations[i]['color'] = 'red';
}
p.markModified('variations');
p.save(function(err) { ...
这篇关于无法更新mongoose模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!