npm install marklogic) and require it from your Node app. For example,
Remote data access is cheap, but not free, even in Node.js. Some code needs to run closer to the data.
"Remote calls are more expensive than in-process calls, and thus remote APIs need to be coarser-grained, which is often more awkward to use. If you need to change the allocation of responsibilities between components, such movements of behavior are harder to do when you’re crossing process boundaries."
"But I thought it was bad practice to put business logic in my database? Isn’t that the job of the application tier?"
The code below illustrates the most basic concepts, inserting, querying, and updating JSON in MarkLogic. For more details on the rich set of APIs available, consult the expansive API and usage docs.
This query inserts two new JSON documents into the database. In this case, each document represents a character from the popular American television show, "The Muppets". As such, the code adds them to the
muppets collection, so you can easily ask for all Muppets later.
All inserts and updates happen transactionally. Thus, if there’s an error midway through the execution of your code, you can be assured that any changes that were initiated will automatically be rolled back. You can try this by throwing an
Error somewhere in the code, such as in the second iteration of the loop.
Now that the JSON documents are stored in the database, you can query them.
This query returns a report of all the documents that match the
where(), similar to how the
WHERE clause works in a SQL query. In this case, the query uses query by example (
qbe) to match a representative instance.
Not only do you get back the matched documents themselves, but also some additional information about the match, much like the statistics you’d get from a search engine. The ability to combine database and search engine-style queries is a key advantage of MarkLogic.
As a database, you also need to be able to update documents. In this case, the example updates one particular document to add a new
demeanor property, using the query above.
Documents in the database are stored as trees of
Nodes. This generalizes across JSON and XML. As an optimization for performance and consistency, Nodes are immutable. This means that when you get a JSON document out of the database for update, the pattern is
- Convert the document (
obj.demeanor = 'cantankerous')
- Then finally save it back to the database as a new Node, replacing the existing one (
Finally, clean up by removing the documents in the
muppets collection that you just created.