Accessing Couchbase Lite from React Native
The first thing you need to do to access Couchbase Lite database is to open it:
import CouchbaseLite from 'react-native-cbl'
CouchbaseLite.openDb('mydbname').then( () => {
//when database is opened
})
When database is opened you can perform all the standard crud operations on documents:
//load document from database
CouchbaseLite.getDocument('document-id').then( docProperties => {} )
//create document with autogenerated id
CouchbaseLite.createDocument('document-id').then( docId => {} )
//update document
CouchbaseLite.updateDocument('document-id', { key: 'value' }).then( () => {} )
//update document with autogenerated id
CouchbaseLite.deleteDocument('document-id').then( () => {} )
Retrieving collection of documents is a bit more tricky. First you need to supply view you're going to query. View is defined by map function which says Couchbase Lite which documents you want to get and in which order:
CouchbaseLite.openDb('mydbname').then( () => {
CouchbaseLite.updateDocument(
'_design/main', {
views: {
notes: {
map: function(doc) {
if (doc.docType == 'note') {
emit(doc.createdTime, null)
}
}.toString(),
},
}
})
})
After that you can query defined view:
CouchbaseLite.query('notes', { descending: true })
Parameter descending
makes the Couchbase return documents in reverse order. There are some other parameters you can provide to query method to modify the way documents are returned.