A collection stores documents of the same type.
To create a collection you need a RxDatabase-Object which has the .collection()-method. Every colletion needs a collection-name and a RxSchema.
myDatabase.collection({
name: 'humans',
schema: mySchema
})
.then(collection => console.dir(collection));The name identifies the collection and should be used to refind the collection in the database. Two different collections in the same database can never have the same name.
The schema defines how your data looks and how it should be handled. You can pass a RxSchema-Object or a simple javascript-object from which the schema will be generated.
To get an existing collection from the database, call the collection-name directly on the database:
const collection = await db.collection('heroes');
const collection2 = db.heroes;
console.log(collection == collection2);
// trueCalling this will return an rxjs-Observable which streams every change to data of this collection.
myCollection.$.subscribe(changeEvent => console.dir(changeEvent));Use this to insert new documents to the database. The collection will validate the schema and encrypt the encrypted fields by itself. Returns the new RxDocument.
const doc = await myCollection.insert({
name: 'foo',
lastname: 'bar'
});Inserts if documents does not exsits. Overwrites if document exists. Returns the new or overwritten RxDocument.
const doc = await myCollection.upsert({
name: 'foo',
lastname: 'bar2'
});To find documents in your collection, use this method. This will return a RxQuery-Object with the exec-function.
// directly pass search-object
myCollection.find({name: {$eq: 'foo'}})
.exec().then(documents => console.dir(documents));
// chain querys
myCollection.find().where('name').eq('foo')
.exec().then(documents => console.dir(documents));This does basically what find() does, but it returns only a single document. You can pass a primary-value to esier find a single document.
// get document with name:foobar
myCollection.findOne().where('name').eq('foo')
.exec().then(doc => console.dir(doc));
// get document by primary
myCollection.findOne('foo')
.exec().then(doc => console.dir(doc));Use this function to create a json-export from every document in the collection. You can pass true as parameter to decrypted the encrypted data-fields of your documents.
myCollection.dump()
.then(json => console.dir(json));
// decrypted dump
myCollection.dump(true)
.then(json => console.dir(json));To import the json-dump into your collection, use this function.
// import the dump to the database
myCollection.importDump(json)
.then(() => console.log('done'));To replicate the colletion with another server, use this function. It basically does the same as pouchdb-sync but also add event-handles to make sure that change-events will be recognized.
mycollection.sync('http://localhost:10102/db/');If you are new to RxDB, you should continue here