Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create multiple collections per database?

Switching from mongo to pouchdb (with Cloudant), i like the "one database per user" concept, but is there a way to create multiple collections/tables per database ?

Example

- Peter  
        - History
        - Settings
        - Friends
- John
        - History
        - Settings
        - Friends

etc...

like image 235
Abel Chalier Avatar asked Apr 28 '16 11:04

Abel Chalier


2 Answers

Couchdb does not have the concept of collections. However, you can achieve similar results using type identifiers on your documents in conjunction with Couchdb views.

Type Identifiers

When you save a document in Couchdb add a field that specifies the type. For example, you would store a friend like so:

{
  _id: "XXXX",
  type: "Friend",
  first_name: "John",
  ...
}

And you would store history like this:

{
  _id: "XXXX",
  type: "History",
  url: "http://www.google.com",
  ...
}

Both of these documents would be in the same database, and if you queried all documents on that database then you would receive both.

Views

You can create views that filter on type and then query those views directly. For example, create a view to retrieve friends like so (in Cloudant you can go to add new Design Document and you can copy and paste this directly):

{
  "_id" : "_design/friends",
  "views" : {
    "all" : {
      "map" : "function(doc){ if (doc.type && doc.type == 'Friend') { emit(doc._id, doc._rev)}}"
    }
  }
}

Let's expand the map function:

function(doc) {
  if (doc.type && doc.type == "Friend") {
    emit(doc._id, doc._rev);
  }
}

Essentially this map function is saying to only associate documents to this view that have type == "Friend". Now, we can query this view and only friends will be returned:

http://SERVER/DATABASE/_design/friends/_view/all

Where friends = name of the design document and all = name of the view. Replace SERVER with your server and DATABASE with your database name.

You can find more information about views here:

https://wiki.apache.org/couchdb/Introduction_to_CouchDB_views

like image 177
markwatsonatx Avatar answered Nov 19 '22 00:11

markwatsonatx


You could look into relational-pouch for something like this. Else you could do "3 databases per user." ;)

like image 5
nlawson Avatar answered Nov 18 '22 23:11

nlawson