Simple field query? - node.js

I'm using nano to connect to couchDB through node.js; I have read the basic documentation for couch.db and understand it for the most part, but I didn't see a simple query function anywhere. All I would like to do is (from my server), get the value of a field , from a specific document. How would I do this?
Additionally, while looking for the answer to this, I ran across one site that said an html page can directly send a GET to the DB to get values; I thought the database was secure though, so how is this possible? I guess I'm missing something big here.

The simplest way to get a specific document by id is using the get method. This will return you the document itself:
var Nano = require('nano'),
db = new Nano('http://admin:password#localhost:5984').use(yourDatabase),
db.get(yourDocumentId, function (err, yourDocument, headers) {
return console.log(err || yourDocument);
});
Re your second question about a webpage requesting data straight from CouchDB: this can be done securely as long as you have a login specifically for your end user in CouchDB. Your end user would log in to CouchDB and CouchDB would return a cookie which your browser would send on each subsequent request to CouchDB as a way of authenticating itself.
see http://guide.couchdb.org/editions/1/en/security.html#cookies for more info.
Personally I would not use this approach as it makes it too easy to couple your UI to your data making future changes harder. I would recommend creating a REST api in express and call that from your UI. It will keep your UI code more focused on UI logic and your api implementation focused on dealing with CouchDB document and view operations.

Related

Node.js: Is there an advantage to populating page data using Socket.io vs res.render(), or vice-versa?

Let's say, hypothetically, I am working on a website which provides live score updates for sporting fixtures.
A script checks an external API for updates every few seconds. If there is a new update, the information is saved to a database, and then pushed out to the user.
When a new user accesses the website, a script queries the database and populates the page with all the information ingested so far.
I am using socket.io to push live updates. However, when someone is accessing the page for the first time, I have a couple of options:
I could use the existing socket.io infrastructure to populate the page
I could request the information when routing the user, pass it into res.render() as an argument and render the data using, for example, Pug.
In this circumstance, my instinct would be to utilise the existing socket.io infrastructure; purely because it would save me writing additional code. However, I am curious to know whether there are any other reasons for, or against, using either approach. For example, would it be more performant to render the data, initially, using one approach or the other?

Querying ArangoDB without leaving page

I'm relatively new to webdevelopment and have been using ArangoDB for most of that limited experience. I have a basic understanding of Node.js and creating express based CRUD apps with ArangoDB as the database.
I'm getting to a point though where I'd like to have the ability to query the database from inside the client. Say I would like to have a datalist-type element where the user types words into a searchbar. I'd like the ability to query the database from there rather than having to query the database for all of its files prior to creating the datalist. I have not found a single mention though of using database queries from the client side. I can't imagine that this is not possible. Surely when I search wikipedia through the search bar and it provides me with options I didn't just receive the entire wikipedia documents list upon loading the page? Please steer me in the right direction, I don't know how to tackle this problem.
Have a look at how to build dynamic forms, this will allow you to perform AJAX style calls from the browser window to a back end REST API service. This will allow your back end web service to gather the data for the response (from ArangoDB if required), and respond with that data, most likely in a JSON format.
Your UI can then take that response and dynamically update components in your DOM so that the user can see the data injected into the page without a page reload action taking place.
https://www.pluralsight.com/search?q=ajax is a great place to start.
Alternatively you can have a look at free content like https://www.youtube.com/watch?v=tNKD0kfel6o

GETting a document within a Document Update Handler

Is it possible to query (GET) a document from within a document update handler in CouchDB?
I have written a simple document update handler in CouchDB 2.0 to accept a POST from a third party (CognitoForms). This works fine, and I take the ID from their JSON payload and use that as the doc _id.
You can then specify an 'update' URI in CognitoForms, so I could create a new update handler or use the same one. However, in CognitoForms:
The update does a POST rather than a PUT
There does not appear to be a way to send any query parameters
As the ID for the document which needs to be updated is within the body, I could use this to query the database for the document, get the _rev, and return the payload with the _id and _rev to perform the update. However, I simply don't know if I can do such a query within the update handler. I feel like I am either missing something obvious, or there is a very good reason that I wouldn't be allowed to do that.
Thanks very much
edit: I should add that I understand I could create a small application to parse the request before forwarding on to couchdb, but I was interested to see if I could implement this in couchdb only to understand how far I can get without another layer!
In your particular case, it's quite hard to do this. A document update handler is basically a pure function that gets the data it needs and returns a response, but it has no way to reach out into the database.
If you add a doc id to the url, the update function gets the doc from the database as a parameter. For details see the CouchDB docs for update functions.
The way to a possible solution is to use a rewrite in CouchDB in order to extract the id from the body. In CouchDB 2.0, a new way for rewrites as functions has been introduced.
For pushing the limits, using a rewrite function for this sounds like fun. But for a production use case, it's probably easier and more maintainable to create a small node.js app that parses the body.

Real-Time Database Messaging

We've got an application in Django running against a PGSQL database. One of the functions we've grown to support is real-time messaging to our UI when data is updated in the backend DB.
So... for example we show the contents of a customer table in our UI, as records are added/removed/updated from the backend customer DB table we echo those updates to our UI in real-time via some redis/socket.io/node.js magic.
Currently we've rolled our own solution for this entire thing using overloaded save() methods on the Django table models. That actually works pretty well for our current functions but as tables continue to grow into GB's of data, it is starting to slow down on some larger tables as our engine digs through the current 'subscribed' UI's and messages out appropriately which updates are needed as which clients.
Curious what other options might exist here. I believe MongoDB and other no-sql type engines support some constructs like this out of the box but I'm not finding an exact hit when Googling for better solutions.
Currently we've rolled our own solution for this entire thing using
overloaded save() methods on the Django table models.
Instead of working on the app level you might want to work on the lower, database level.
Add a PostgreSQL trigger after row insertion, and use pg_notify to notify external apps of the change.
Then in NodeJS:
var PGPubsub = require('pg-pubsub');
var pubsubInstance = new PGPubsub('postgres://username#localhost/tablename');
pubsubInstance.addChannel('channelName', function (channelPayload) {
// Handle the notification and its payload
// If the payload was JSON it has already been parsed for you
});
See that and that.
And you will be able to to the same in Python https://pypi.python.org/pypi/pgpubsub/0.0.2.
Finally, you might want to use data-partitioning in PostgreSQL. Long story short, PostgreSQL has already everything you need :)

Restify: Passing User Data

I am writing service using NodeJS + Restify. I have split each actual service into separate file (what, I assume, everyone is doing). They all are going to be using mysql database so I thought I could open a single connection to database which could be used by each service rather than opening connections every time a request is done.
The problem is that I don't seem to find a way to pass user data. By user data I mean any custom data that would be accessible by every service callbacked by the server.
I primarily use NodeJS + Express, but having looked through some of the documentation of Restify, I believe you could use the authorization parser (under Bundled Plugins on their site: click here to go there)
I think that would be the most basic way to pass user data.
I haven't tested it but, I believe you'd just add this to use it:
server.use(restify.authorizationParser());
You could then access the user data with:
//This is based on the structure of req.authorization in the documentation.
req.authorization.basic.user
I believe you could set new user data (when the user logs in or something) like:
req.authorization.id = 'id'

Resources