Showing posts with label pouchdb. Show all posts
Showing posts with label pouchdb. Show all posts

Tuesday, October 9, 2018

How to get specific data (from an Array) using PouchDB-Find

Leave a Comment

CouchDB document:

  "members": [     {       "name": "Mark",       "age": 35,     },     {       "name": "Bill",       "age": 32,     }   ] 

DB Query from PouchDB using PouchDB-Find:

  db.createIndex({     index: {fields: [       '_id',       'members.[].name'     ]}   }).then(() => {     db.find({       'selector': {         '_id': { '$gt': null },         'members': {           '$elemMatch': {             'name': {'$eq': 'Bill'}           }         }       },       'fields': [         'members'       ]     }).then((result) => {       console.log(result)     }).catch((err) => {       console.log(err)     })   }) 

The result I get from the above query is the Members array as the whole. But I need to get only the below when I request "name" as "Bill" not the complete array.

{   "name": "Bill",   "age": 32, } 

I did try the fields section in the query but I am unable to find what should be mentioned to get what I want.

1 Answers

Answers 1

It is only possible to specify a set of index independent (static) fields in the doc for find to pick once your selector has chosen a given doc.

Mango queries are a simplified syntax to do common cases and when the structure of your indexes and queries is not typical, you need to use map/reduce directly as indicated in the docs:

The map/reduce API is designed for cases that are too complex for Mango queries

So your changes to the first map/reduce example would look something like:

function mapFun(doc) {     if (doc.members)       doc.members.forEach( function(m) {         emit(m.name, m);  // key is name, value is the individual member Object       });   }.toString()   ...   return db.query('index', {     key: 'Bill',     include_docs: false   }); 

To get output like:

 {   "offset" : 0,   "rows": [{     "id": "somedoc",     "key": "Bill",     "value": {name:'Bill', age:32}   }],   "total_rows" : 1 } 
Read More

Tuesday, August 14, 2018

pouchdb db.login is not a function

Leave a Comment

Tried using these imports

import PouchDB from 'pouchdb'; import PouchDBAuth from 'pouchdb-authentication';  PouchDB.plugin(PouchDBAuth) 

Module ''pouchdb-authentication'' has no default export is the error generated while using these imports.

PouchDB.plugin(require('pouchdb-authentication')); 

Using require is removing the error but still showing db.login() is not a function.Can anyone suggest where the issue is?

1 Answers

Answers 1

Well I found why it was not working in my situation, I was using this :

import '*' as PouchDBAuthentication from 'pouchdb-authentication'; 

instead of

import PouchDBAuthentication from 'pouchdb-authentication'; 

So the right way is

import PouchDBAuthentication from 'pouchdb-authentication'; import PouchDB from 'pouchdb';  PouchDB.plugin(PouchDBAuthentication); 

In the second hand the following steps should be done : https://github.com/pouchdb-community/pouchdb-authentication/issues/211

Read More

Friday, April 27, 2018

System freezes when parent and child connectivity

Leave a Comment

I have used Pouchdb with Electron, connected two system through local LAN and using the single database which is a parent and another child system will be using the same pouchdb database.

used express-pouch to make child system to connect parent pouchdb.

There is background sync will be running in parent system from couchDB to pouchDB.

The connection is working as expected, Problem will be after some time of connection system freezes in both parent and child. checked task manager disk 100%, memory 100%.

Both System - windows 10 pro - Ram - 4GB

1 Answers

Answers 1

Try to increase memory allocated for your script with the option --max_old_space_size=<size>.

Try too to monitor number of emitter you have with method emitter.getMaxListeners() and emitter.listenerCount(eventName), and increase the number with emitter.setMaxListener(n)

Read More

Saturday, December 16, 2017

PouchDB in Electron, set data storage location

Leave a Comment

I am writing an Electron application that will need to store a large amount of data on the client. I want to use PouchDB but I need to have control over the location where the database is held on the user's PC. I can't find anything in the docs about it.

1 Answers

Answers 1

Setting the location of the database is very simple.

db = new PouchDB(dbFilePath); 

You can set the dbFilePath to the path that you want. For example, I want to set the path to where the Electron application runs. So I do the following.

const appDataDirectory = app.getPath('appData'); let dbFilePath = appDataDirectory + '/data/'; if (process.env.NODE_ENV === 'development') {   dbFilePath = './data/'; } log.debug('NODE_ENV:%s, dbFilePath:%s', process.env.NODE_ENV, dbFilePath); let db = new PouchDB(dbFilePath); 
Read More

Saturday, August 26, 2017

how can I generate a partially unique and sequential field in a couchdb document?

Leave a Comment

I'm very new to couchdb and I'm wondering how I can create ID's that look like.

Employee:DBX-**0001**-SP

the number portion 0001 must be unique and sequential. How can I achieve something like this in couchdb? I searched all over and I cannot find any simple solution.

It would be best if I can generate the sequential portion in couchdb and not on the client side to avoid collisions during replication.

The current solution I have is that I fetch a document I've stored that looks like this {"_id": "EmployeeAutoIncrement", value: 1} upon retrieval I increment the value and send it back to the server if those are successful then I return the new incremented value and use it as my Auto Increment Value to be part of the ID Employee:DBX-AUTO_INCREMENT_VALUE_HERE-SP

The issue with this is that if two people make a request to the EmployeeAutoIncrement at the same time and they both update it will it not cause conflicts? Also, if one person makes a request and they go offline then they come back online then wouldn't that also make a conflict?

2 Answers

Answers 1

All of the requirements cannot be satisfied client-side when using multiple clients, some of which might be off-line.

Here is a process that results in a monotonically-increasing id:

  1. Each client saves a record with a unique id. The record should include a flag marking the record as temporary.
  2. Build an external process that listens to the changes feed for records marked as temporary. The changes feed outputs records in "time order of application".
  3. The external process should create a new record with the correct id, flagging it as permanent. Since only that process creates "permanent" records, it can read and write the EmployeeAutoIncrement value without collisions.
  4. The external process can then delete the temporary record.

The database will have double the number of records, so it will grow more quickly and need to be compacted sooner if space is an issue. Any views/queries on the employee records will need to check for the permanent flag, in case a query runs while the external process is adding a new record.

Answers 2

It can (sort of) be done, although I recommend you think about your design choices and why you want this done on a distributed database -- it's probably better done on the client where you can control the serialization to your sequence generator.

If you want to do it at least partially on the server, you will need an implementation of a so-called CRDT counter, as outlined in the following paper:

http://hal.upmc.fr/docs/00/55/55/88/PDF/techreport.pdf

You can find a Ruby implementation of some of those ideas here:

https://github.com/aphyr/meangirls

and a simple Couch-specific implementation of a counter (the one you need) and a set here:

https://github.com/drsm79/couch-crdt

The latter, whilst written in Python, will do almost exactly what you want, if you follow the pattern as shown in the following example:

https://github.com/drsm79/couch-crdt/blob/master/examples/counter.py

which will give you your monotonic sequence. From there, create your document _id.

Translation to JavaScript and PouchDB left as an exercise for the reader.

Read More

Wednesday, February 8, 2017

Best approach on handling large dataset for offline-first Mobile Apps (PouchDB)

Leave a Comment

So I'm using Ionic v2 and using Pouch for mobile development using sqlite. Data coming from a REST API which contains something like this:

{   "record-id": "2332255",   "record-name": "record-ABC-XTY",   "record-items": [     {       "item-id": "456454",       "item-name": "item-XADD",       "category": "Cat1",       "subcategory": "Subcat1",       "location": "LocationXYZ",       "owner": "Person1",       "data-rows": [         {           "row-name": "sampleRowName1",           "row-value": "ABC-XASS"         },         {           "row-name": "sampleRowName2",           "row-value": "ABC-XASS"         }       ]     },     {       "item-id": "654645",       "item-name": "item-BNSSA",       "category": "Cat2",       "subcategory": "Subcat2",       "location": "LocationABC",       "owner": "Person2",       "data-rows": [         {           "row-name": "sampleRowName1",           "row-value": "ABC-XASS"         },         {           "row-name": "sampleRowName2",           "row-value": "ABC-XASS"         }       ]     }   ] } 

Now as you can see, the record-items could contain 100,000 items or more (est json size: 32mb). Right now I'm lost on which approach should I take. Optimized data handling is crucial and I don't know what PouchDB approach is better. Here are some of my thoughts.

  1. Save the whole JSON data as one entry for PouchDB. But I'm worried that it will take up a large memory when retrieved and will make that application slow.
  2. Chunk the record-items by one pouch entry record and retrieve it individually. I'm not sure if this is better in terms of overall performance but PouchDB record will probably be larger (?).

Also, there will be sorting, fetching all data (only the _ids and few fields just to show a list of all results) and searching.

2 Answers

Answers 1

We have a similar app that works in offline mode and stores the data locally using sqlite but the data we deal with may not be that huge. For us the data is downloaded as xml file from web service; the xml have attributes row, column, value, name etc. The app serializes the data and converts it into objects which are then inserted into sqlite (using "InsertAll"/"UpdateAll" the insert or update for items is quite fast). These xml's are loaded into UI and user can update "value" tags from UI.
Search is optimized by giving user filters so that the query is run on smaller data.

For your case I can think of 3 tables that you can use:-

1) Records (Fields:-RecordID, RecordName) 2) Items (Fields:- ItemID (PK), RecordID (FK), ItemName etc) 3) Rows (Fields:-ItemID (FK), RowName, RowValue)

After geting data from REST you can serialize the data and insert it into respective tables concurrently. Try giving users filters when it comes to search so that actual data set is smaller.

Hope it helps!

Answers 2

Your basic decision is whether to embed the data or reference it. Here are some general rules for deciding:

Embed when:

  • Data typically queried together (example: user profile)
  • Child depends on parent
  • One-to-one relationship
  • One-to-few relationship
  • Changes occur at a similar rate

Reference when:

  • Unbounded one-to-many relationship exists
  • Many-to-many relationship
  • Same data repeated in many places
  • Data changes at different rates

You're correct that if you store everything as one record you may have problems with the size. The extra storage caused by splitting it up should be inconsequential.

You'll be using views to create indexes, which then feed into your queries. How you do that will probably dominate the efficiency.

Read More

Sunday, April 17, 2016

Authenticating a CouchDB user against an external server

Leave a Comment

I have the following setup:

  1. CouchDB database that stores users and handles authentication; creates one db per user
  2. Web app that uses PouchDB to sync and authenticate via pouchdb-authentication
  3. A REST API server that gets requests from the web app and accesses CouchDB

Now, the REST API has admin access to CouchDB, so when it receives requests, it needs to do some form of authentication to make sure the sender has permissions to the database he claims to have access to. Since I use persistent sessions, the web app does not know the user password at all times (unless I store it in localstorage - obviously a bad idea). The session cookie is HttpOnly, so I can't access it.

What would be the best way to authenticate requests to the API under this scenario?

0 Answers

Read More

Tuesday, March 15, 2016

How to encrypt a pouchdb database

Leave a Comment

Background:

I am trying to encrypt a pouchdb database by using crypto-pouch library. I had a look at the example shown at https://github.com/calvinmetcalf/crypto-pouch But it doesn't seem to do anything for me.

My code:

<!DOCTYPE html>  <html ng-app="pouchdbApp">   <head>     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>     <script src="pouchdbDemo.js"></script>     <script src="http://cdn.jsdelivr.net/pouchdb/5.2.1/pouchdb.min.js"></script>     <!-- <script src="crypto-pouch-master/bundle.js"></script> -->     <script src="http://wzrd.in/standalone/crypto-pouch"></script>       <script>         var db = new PouchDB('kittens2');           var password = "mypassword";          db.crypto(password).then(function (publicKey) {              console.log("publicKey");     	    console.log(publicKey);         });              /* db.removeCrypto();  */           var doc = {  		  "_id": "mittens",  		  "name": "Mittens",  		  "occupation": "kitten",  		  "age": 3,  		  "hobbies": [  		    "playing with balls of yarn",  		    "chasing laser pointers",  		    "lookin' hella cute"   		   ]  		};                db.put(doc);          db.get('mittens').then(function (doc) {           console.log(doc);        });       </script>     </head>   <body>     </body>    </html>

But my code doesn't see to do any encryption of the data entered, or i couldn't see any public key generated.

Any clue how i should be using the crypto-pouch library with pouchdb.

1 Answers

Answers 1

so the documentation is a bit confusing (which I just cleaned up) but when you call db.crypto it wraps the database so that documents are transparently encrypted and decrypted

db.crypto(password).then(function () {    // <-- encryption set up }) 

and it will transparently encrypt documents you create and decrypt ones you read until you call

db.removeCrypto(); 

so if you want to test do something like

db.crypto(password).then(function () {    return db.put({_id: 'foo', bar: 'baz'}); }).then(function () {     return db.get('foo'); }).then(function (doc) {     console.log('decrypted', doc);     return db.removeCrypto(); }).then(function () {     return db.get('foo'); }).then(function (doc) {     console.log('encrypted', doc); }) 
Read More