使用 MarkLogic Patch Builder 在 JSON 数组的末尾插入一个新的数组项

Insert a new array item at the end of JSON array using MarkLogic Patch Builder

我的 MarkLogic 数据库中有一个 cities.json 文件,如下所示:

[
    { city: "New York", pop: "8.538 million (2016)"},
    { city: "Miami", pop: "453,579 (2016)"}
]

在 Node.js 中使用 MarkLogic Patch Builder,我想在数组末尾追加一个城市项目。

db.documents.patch('cities.json',

    pb.insert('array-node("/")', 'last-child', { city: "Denver", pop: 682,545 (2015) })

).result();

然而这似乎没有更新 cities.json 文件。

我也试过:

pb.insert('/array-node()', 'last-child', { city: "Denver", pop: 682,545 (2015) })

pb.insert('/array-node("/")', 'last-child', { city: "Denver", pop: 682,545 (2015) })

但运气不好。

我一直在阅读本手册 (https://docs.marklogic.com/guide/node-dev/partial-update#id_65749) 并尝试使用 array-node() 到 select 父数组。我注意到手册中提供的所有示例都要求数组具有 属性 名称。没有示例如何 select 数组是 JSON.

的父元素

请注意,如果我将 cities.json 文件更改为:

{
    "cities": [
        { city: "New York", pop: "8.538 million (2016)"},
        { city: "Miami", pop: "453,579 (2016)"}
    ]
}

和 Patch Builder 声明:

pb.insert('/array-node("cities")', 'last-child', { city: "Denver", pop: 682,545 (2015) })

它按预期工作,但我真的更愿意让我的 JSON 像数组一样简单。

提前致谢!

在底层,Node.js 客户端 API 使用 MarkLogic REST API,如果你打开它的文档,你会找到关于 limitations working with JSON documents 的部分。

本节解释了无法在 "anonymous" 根 属性 后立即插入 属性。 (这将是一个 JSON 文档,其中没有命名根 属性)。

目前您最好的选择是检索文档,在 JavaScript 代码中进行更新并重新插入文档。这可以通过以下方式实现:

const uri = '/cities.json';
db.documents.read(uri).result()
.then(response => {
  const document = response[0].content;
  document.push({ city: 'Denver', pop: '682,545 (2015)' });
  return db.documents.write({ uri, content: document }).result();
})
.then(response => console.info(response))
.catch(error => console.error(error));