使用 JSON 补丁验证 Mongoose 数组更新
Validating Mongoose Array Updates with JSON Patch
我目前正在构建一个 API,它使用 JSON 补丁规范使用 Mongoose ORM 对 MongoDB 进行部分更新。
我正在使用节点模块 mongoose-json-patch 将补丁应用到我的文档,如下所示:
var patchUpdate = function(req, res){
var patches = req.body;
var id = req.params.id;
User.findById(id, function(err, user){
if(err){ res.send(err);}
user.patch(patches, function(err){
if(err){ res.send(err);}
user.save(function(err){
if(err) {res.send(err);}
else {res.send("Update(s) successful" + user);}
});
});
});
};
当我尝试使用 JSON 补丁语法删除或替换数组元素时,我的主要问题出现了:
var patches = [{"op":"replace", "path": "/interests/0", "value":"Working"}]
var user = {
name: "Chad",
interests: ["Walking", "Eating", "Driving"]
}
这应该用新值 ("Working") 替换数组中的第一项 ("Walking"),但是我不知道如何验证实际被替换的内容。如果另一个请求在应用补丁之前删除了 /interests/0,"Eating" 将被替换为 "Working" 而不是 "Walking",后者将不再存在于数组中。
我想确定如果客户认为他正在编辑 "Walking",那么他要么会成功编辑它,要么至少会出错。
在 运行 我自己遇到同样的问题后,我将分享我的解决方案。规范(描述为 here)描述了六个操作,其中一个是测试。消息来源将测试操作描述为
Tests that the specified value is set in the document. If the test fails, then the patch as a whole should not apply.
为确保您更改的值符合您的预期,您应该验证数据的状态。您可以通过在替换或删除操作之前执行测试操作来执行此操作,其中值等于预期的数据状态。如果测试失败,则不会执行以下操作。
通过测试操作,您的补丁数据将如下所示:
var patches = [
{"op":"test", "path": "/interests/0", "value": currentValue}, //where currentValue is the expected value
{"op":"replace", "path": "/interests/0", "value":"Working"}
]
我目前正在构建一个 API,它使用 JSON 补丁规范使用 Mongoose ORM 对 MongoDB 进行部分更新。
我正在使用节点模块 mongoose-json-patch 将补丁应用到我的文档,如下所示:
var patchUpdate = function(req, res){
var patches = req.body;
var id = req.params.id;
User.findById(id, function(err, user){
if(err){ res.send(err);}
user.patch(patches, function(err){
if(err){ res.send(err);}
user.save(function(err){
if(err) {res.send(err);}
else {res.send("Update(s) successful" + user);}
});
});
});
};
当我尝试使用 JSON 补丁语法删除或替换数组元素时,我的主要问题出现了:
var patches = [{"op":"replace", "path": "/interests/0", "value":"Working"}]
var user = {
name: "Chad",
interests: ["Walking", "Eating", "Driving"]
}
这应该用新值 ("Working") 替换数组中的第一项 ("Walking"),但是我不知道如何验证实际被替换的内容。如果另一个请求在应用补丁之前删除了 /interests/0,"Eating" 将被替换为 "Working" 而不是 "Walking",后者将不再存在于数组中。
我想确定如果客户认为他正在编辑 "Walking",那么他要么会成功编辑它,要么至少会出错。
在 运行 我自己遇到同样的问题后,我将分享我的解决方案。规范(描述为 here)描述了六个操作,其中一个是测试。消息来源将测试操作描述为
Tests that the specified value is set in the document. If the test fails, then the patch as a whole should not apply.
为确保您更改的值符合您的预期,您应该验证数据的状态。您可以通过在替换或删除操作之前执行测试操作来执行此操作,其中值等于预期的数据状态。如果测试失败,则不会执行以下操作。
通过测试操作,您的补丁数据将如下所示:
var patches = [
{"op":"test", "path": "/interests/0", "value": currentValue}, //where currentValue is the expected value
{"op":"replace", "path": "/interests/0", "value":"Working"}
]