我的一块蒙戈文档结构是:MongooseJS弄乱当文档被更新前的进口数据
{ "_id": ObjectId("xxxxxx..."),
"Country" : "UNITED KINGDOM",
"Line" : "something",
"Records" : [
{"rdata" : "foo", "rtype" : "X", "name" : "John"},
{"rdata" : "bar", "rtype" : "Y", "name" : "Bill"}
], ...
我用猫鼬通过以下模型来访问数据:
var Record = new Schema({
rdata: String,
rtype: String,
name: String
}, {_id: false});
var ThingSchema = new Schema({
Country: String,
Line : String,
Records : [Record],
比方说,我想通过向合适的API URL发送PUT请求来更新我的文档之一的“行”属性,从"Line" : "something"
到"Line" : "way more interesting"
。我可以看到发送的数据是正确的。这是API做什么:
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Thing.findById(req.params.id, function (err, thing) {
if (err) { return handleError(res, err); }
if(!thing) { return res.send(404); }
var updated = _.merge(thing, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, updated);
});
});
};
的API回来与200/OK - 但我看到下面的更新的数据:
{ "_id": ObjectId("xxxxxx..."),
"Country" : "UNITED KINGDOM",
"Line" : "way more interesting", <-- updated correctly
"Records" : [
{"rdata" : "foo", "rtype" : "X", "name" : "John"},
{"rdata" : "foo", "rtype" : "X", "name" : "John"}
], ...
通知,记录阵列是怎么通过覆盖搞砸了我通过复制第一个记录来记录第二个记录。 (如果我打开Mongoose自动添加'_id'到子文档,那么即使数组中的两个记录中的“_id”字段也是相同的)。
它可能是相关的,最初的记录不是通过Mongoose添加 - 而是通过导入JSON文档。任何有关如何开始发现这种情况的建议都会很棒。
好极了,谢谢! –
@ tom.W不用担心:-) – chridam