Reputation: 645
I have a cities.json
file in my MarkLogic database which looks like:
[
{ city: "New York", pop: "8.538 million (2016)"},
{ city: "Miami", pop: "453,579 (2016)"}
]
Using MarkLogic Patch Builder in Node.js, I would like to append one more city item to the end of the array.
db.documents.patch('cities.json',
pb.insert('array-node("/")', 'last-child', { city: "Denver", pop: 682,545 (2015) })
).result();
However this does not seem to update cities.json
file.
I also tried:
pb.insert('/array-node()', 'last-child', { city: "Denver", pop: 682,545 (2015) })
pb.insert('/array-node("/")', 'last-child', { city: "Denver", pop: 682,545 (2015) })
but no luck.
I've been reading this manual (https://docs.marklogic.com/guide/node-dev/partial-update#id_65749) and tried to use array-node()
to select parent array. I notice that all the examples provided in the manual require array to have a property name. There is no example how to select array that is the parent element of the JSON.
Note that if I change my cities.json
file to:
{
"cities": [
{ city: "New York", pop: "8.538 million (2016)"},
{ city: "Miami", pop: "453,579 (2016)"}
]
}
and Patch Builder statement to:
pb.insert('/array-node("cities")', 'last-child', { city: "Denver", pop: 682,545 (2015) })
it is working as expected, however I would really prefer to keep my JSON simple as an array.
Thanks in advance!
Upvotes: 3
Views: 1035
Reputation: 11214
Under the hood the Node.js Client API uses the MarkLogic REST API and if you hit up its documentation you'll find a section on limitations working with JSON documents.
In this section it is explained that it's not possible to insert a property immediately after an "anonymous" root property. (This would be a JSON document where there's no named root property).
Your best option at the moment would be to retrieve the document, do the update in your JavaScript code and reinsert the document. This could be achieved in the following way:
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));
Upvotes: 2