我使用TAFFYDB创建了一个数据模型.某些字段具有嵌套记录.我在查询和更新嵌套记录时遇到困难.
例如:
var friends = TAFFY([
{
"id":1,
"gender":"M",
"first":"John",
"last":"Smith",
"city":"Seattle, WA",
"comp":
[
{
"id":1,
"audience":"cavern"
},
{
"id":2,
"audience":"cottage"
}
]
},
{
"id":2,
"gender":"F",
"first":"Basic",
"last":"Smith",
"city":"Seattle, WA",
"comp":
[
{
"id":1,
"audience":"bush"
},
{
"id":2,
"audience":"swamp"
}
]
}
]);
假设我需要更新任何comp领域的观众,我将如何进行?
最佳答案 关于查询:
如果有更简单的嵌套数组,则应该能够使用has和hasAll方法选择特定记录.但是,有一个open issue表明这些方法都不能正常工作.有提交,但由于问题已经公开,我认为它们不是100%修复的.
对于复杂的嵌套数据,就像你的例子一样,我发现的唯一一件事是this old mailing list conversation谈论某种find方法.似乎没有这样的方法存在,但在文档中也没有提及它.
关于更新:
您应该能够通过将修改后的JSON(假设您能够从数据库中获取数据)传入正常更新来更新“comp”数据.但是,有一个open bug显示当记录值是对象时更新不起作用.因此,即使您能够查询数据并且能够对其进行修改,由于该错误,您仍无法更新记录.但是,您可以执行删除和插入操作.
尽管我在上面找到了,但我做了一些测试,发现你可以通过传入对象来更新文件.所以这是一个如何进行简单更新的简单示例:
// To show what TAFFYDB looks like:
console.log(friends().stringify());
“[{“id”:1,”gender”:”M”,”first”:”John”,”last”:”Smith”,”city”:”Seattle, WA”,”comp”:[{“id”:1,”audience”:”cavern”},{“id”:2,”audience”:”cottage”}],”___id”:”T000003R000002″,”___s”:true},{“id”:2,”gender”:”F”,”first”:”Basic”,”last”:”Smith”,”city”:”Seattle, WA”,”comp”:[{“id”:1,”audience”:”bush”},{“id”:2,”audience”:”swamp”}],”___id”:”T000003R000003″,”___s”:true}]”
// Get a copy of the comp file from the database for what you want to modify.
// In this example, let's get the **first** record matching people with the name "John Smith":
var johnsComp = friends({first:"John",last:"Smith"}).first().comp;
// Remember, if you want to use select("comp") instead, this will return an array of results.
// So to get the first result, you would need to do this despite there being only one matching result:
// friends({first:"John",last:"Smith"}).select("comp")[0];
// There are no nested queries in TAFFYDB so you need to work with the resulting object as if it were normal javascript.
// You should know the structure and you can either modify things directly, iterate through it, or whatever.
// In this example, I'm just going to change one of the audience values directly:
johnsComp[0].audience = "plains";
// Now let's update that record with the newly modified object.
// Note - if there are more than one "John Smith"s, then all of them will be updated.
friends({first:"John",last:"Smith"}).update({comp:johnsComp});
// To show what TAFFYDB looks like after updating:
console.log(friends().stringify());
“[{“id”:1,”gender”:”M”,”first”:”John”,”last”:”Smith”,”city”:”Seattle, WA”,”comp”:[{“id”:1,”audience”:”plains”},{“id”:2,”audience”:”cottage”}],”___id”:”T000003R000002″,”___s”:true},{“id”:2,”gender”:”F”,”first”:”Basic”,”last”:”Smith”,”city”:”Seattle, WA”,”comp”:[{“id”:1,”audience”:”bush”},{“id”:2,”audience”:”swamp”}],”___id”:”T000003R000003″,”___s”:true}]”
为了更好地进行有针对性的查询或更新(可能类似于嵌套查询/更新),您可以尝试传入函数.如果你看一下docs,对于update()有一个简单的例子:
db().update(function () {this.column = "value";return this;}); // sets column to "value" for all matching records