保存Mongoose文档时出现版本错误 [英] Version error on saving Mongoose docs
问题描述
我有一个问题 - 不确定我做错了什么或者是一个错误。我有一些产品 - 每个产品都有一系列的变化。我想浏览一些数据并将其加载到这些变体中,但我遇到了一些VersionError:找不到匹配的文档错误。
I have an issue - not sure if I am doing something wrong or it's a bug. I have some products - each of these has an array of variations. I want to go through some data and load it in these variations but I experience a number of 'VersionError: No matching document found' errors.
以为我正在参加比赛条件(我按顺序为我修改的每个变体保存相同的文档)我使用asyc.eachSeries()但没有帮助。一次加载导致文档错误的错误不会产生错误,因此它似乎与某些竞争条件有关但我无法追踪它。
Thinking I was having a race condition (I am sequenctially saving the same document for each of its variations that I modify) I used asyc.eachSeries() but that did not help. Loading the error causing documents one at the time does not yield the error so it seems related to some race condition but I cannot track it down.
架构:
var Product = new Schema({
title: {
type: String,
},
variations: {
type: Array
}
});
示例代码:
// Some data to load - the 'variant' is the index of the variations array above
var records = [{
code: 'foo',
id: '50ba9c647abe1789f7000073',
variant: 0
}, {
code: 'bar',
id: '50ba9c647abe1789f7000073',
variant: 1
}, {
code: 'foobar',
id: '50ba9c647abe1789f7000073',
variant: 2
}];
var iterator = function(item, cb) {
Product.findById(item.id).exec(function(err, product) {
if(err) {
return cb(err);
}
if (product) {
product.variations[item.variant].code = item.code.trim();
product.markModified('variations');
product.save(function(err, p) {
return cb(err);
});
} else {
return cb('Missing product');
}
});
};
async.eachSeries(records, iterator, function(err) {
process.exit(1);
});
推荐答案
我认为问题在于你如何定义你的架构。让变体成为自己的模式并让产品模式使用它作为子doc更好。我会改变它看起来像这样:
I think the problem is how you've defined your schema. It's much to better to have variant be it's own schema and have the product schema use that as a sub doc instead. I would change it to look something like this:
var Variant = new Schema({
code: String,
})
var Product = new Schema({
title: String,
variants: [Variant]
})
然后你可以像这样记录:
Then you could go through the records like so:
var variants = product.variants
for (i in variants) {
var variant = variants[i]
variant.code = records[i].code
variant.save(function(err) {
...
})
}
这篇关于保存Mongoose文档时出现版本错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!