RxDB (Reactive Database) is a powerful NoSQL database

RxDB (Reactive Database) is a powerful NoSQL database

2022-10-28 0 1,847
Resource Number 47041 Last Updated 2025-02-21
¥ 0HKD Upgrade VIP
Download Now Matters needing attention
Can't download? Please contact customer service to submit a link error!
Value-added Service: Installation Guide Environment Configuration Secondary Development Template Modification Source Code Installation

The RxDB (short for Reactive Database) recommended in this issue is a NoSQL database for JavaScript applications, Such as websites, hybrid applications, electronic applications, progressive Web applications, and Node.js.

RxDB (Reactive Database) is a powerful NoSQL database插图

Reactive means that you can not only query the current state, but also subscribe to all state changes, such as query results or even individual fields of a document. This is useful for real-time UI-based applications because it is easy to develop and has huge performance benefits. To replicate data between client and server, RxDB provides modules for real-time replication, using any CouchDB-compliant endpoint as well as custom GraphQL endpoints.

RxDB feature

  • Multi-platform support for browsers, nodejs, electron, cordova, react-native, and all other javascript-runtime
  • Responsive data processing based on RxJS
  • Offline priority keeps your app running when users don’t have Internet
  • Replication between client and server data
  • Schema-based json-schema Easy to learn standard
  • Mango-Query is exactly what you know from mongoDB and mongoose
  • Encrypt individual data fields to protect your user data
  • Import/export of database state (json), ideal for encoding using TDD
  • Multiple Windows to synchronize data between different browser Windows or nodejs processes
  • ORM features to easily handle data code relationships and customize documents and collections
  • Full TypeScript support for fast and secure coding (requires Typescript v3.8 or later)

Fast start

Install the RxDB library and RxJS (if not already installed)

npm install rxdb rxjs --save

Create a database using PouchDB RxStorage (you can also use other LokiJS or Dexie.js based storage).

import { createRxDatabase } from 'rxdb';

import { getRxStoragePouch,  addPouchPlugin } from 'rxdb/plugins/pouchdb';
addPouchPlugin(require('pouchdb-adapter-idb'));

const myDatabase = await createRxDatabase({
name: 'heroesdb',
storage: getRxStoragePouch('idb')
}); 

Create schema for collection

const mySchema = {
    title: 'human schema',
    version: 0,
    primaryKey: 'passportId',
    type: 'object',
    properties: {
        passportId: {
            type: 'string',
            maxLength: 100 // <- the primary key must have set maxLength
        },
        firstName: {
            type: 'string'
        },
        lastName: {
            type: 'string'
        },
        age: {
            description: 'age in years',
            type: 'integer',

            // number fields that are used in an index, must have set minium, maximum and multipleOf
            minimum: 0,
            maximum: 150,
            multipleOf: 1
        }
    },
    required: ['firstName', 'lastName', 'passportId'],
    indexes: ['age']
}

Add collection to database

const myCollections = await myDatabase.addCollections({
humans: {
schema: mySchema
},
}); 

Insert document

const myDocument = await myDatabase.humans.insert({
passportId: 'foobar',
firstName: 'Alice',
lastName: 'Bobby',
age: 42
}); 

Subscription document value

myDocument.lastName$.subscribe(lastName =>  {
console.log('lastName is now ' + lastName);
}); 

Query some documents

const foundDocuments = await myDatabase.humans.find({
selector: {
age: {
$gt: 21
}
}
}).exec(); 

Subscription query result

myDatabase.humans.find({
selector: {
age: {
$gt: 21
}
}
}).$.subscribe(documents =>  {
console.log('query has found ' + documents.length +  ' documents');
}); 

Update document

// either via atomicUpdate()
await myDocument.atomicUpdate(data =>  {
data.lastName = 'Carol';
return data;
});

// or via atomicPatch()
await myDocument.atomicPatch({
lastName: 'Carol'
}); 

Delete document

await myDocument.remove(); 

Development mode

The dev-mode plug-in adds a number of checks and validations to RxDB. This ensures that you are using the RxDB API correctly, so you should always use the development mode plug-in when using RxDB in development mode.

  • Adds validation checks for schemas, queries, ORM methods, and document fields.
  • Add a readable error message.
  • Ensure that the readonlyJavaScript object does not mutate accidentally.

Important: The dev-mode plugin will increase your build size and decrease performance. It must always be used in development. You should never use it in production.

import { addRxPlugin } from 'rxdb';
import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';
addRxPlugin(RxDBDevModePlugin);

Used with Node.js

async function createDb() {
if (process.env.NODE_ENV ! == "production") {
await import('rxdb/plugins/dev-mode').then(
module =>  addRxPlugin(module as any)
);
}

const db = createRxDatabase( /* ...  */ );
}

Using with Angular

import { isDevMode } from '@angular/core';

async function createDb() {
if (isDevMode()){
await import('rxdb/plugins/dev-mode').then(
module =>  addRxPlugin(module as any)
);
}
    const db = createRxDatabase( /* ... */ );
    // ...
}

Pattern verification

RxDB has several plug-ins that you can use to ensure that your document data always matches the provided JSON schema.

Note: Schema validation may consume CPU resources and increase build size. You should always use scehma to validate plug-ins in development mode. For most use cases, you should not use validation plug-ins in production.

The validation module performs schema validation when you insert or update aRxDocument or copy document data using the replication plug-in. When validation plug-ins are not used, any document data can be protected, but undefined behavior may occur when data that does not conform to the schema is saved.

< Confirm

The lidate plug-in uses is-my-json-valid for schema validation.

import { addRxPlugin } from 'rxdb';
import { RxDBValidatePlugin } from 'rxdb/plugins/validate';
addRxPlugin(RxDBValidatePlugin); 

ajv- verification

Another validation module that performs schema validation. This one uses ajv as the validator, which is faster. Better compliance with JSON Schema-Standard, but also with larger build sizes.

import { addRxPlugin } from 'rxdb';
import { RxDBAjvValidatePlugin } from 'rxdb/plugins/ajv-validate';
addRxPlugin(RxDBAjvValidatePlugin); 

< p class = “PGC – h – arrow – right” data – track = “82” > < strong > validation – z – mode < / strong > < / p >

is-my-json-valid and ajv-validate are used to perform validations that may not be needed if eval() is not allowed in the content security policy. ‘unsafe-eval’ This uses z-schema as the validator instead of eval.

import { addRxPlugin } from 'rxdb';
import { RxDBValidateZSchemaPlugin } from 'rxdb/plugins/validate-z-schema';
addRxPlugin(RxDBValidateZSchemaPlugin); 

data migration

With RxDB, you can provide a migration strategy for your collection that automatically (or on call) converts existing data from the old schema to the new. This ensures that the customer’s data always matches your latest code version.

< Add migration plug-in

To enable data migration, you must add the Migration plug-in.

import { addRxPlugin } from 'rxdb';
import { RxDBMigrationPlugin } from 'rxdb/plugins/migration';
addRxPlugin(RxDBMigrationPlugin); 

< Provide policy

After creating a collection, you must provide migrationStrategies 0 when the schema’s version number is greater than. To do this, you must add an object to the property that migrationStrategies assigns a function to each schema version. The migrationStrategy is a function that takes the old document data as an argument and returns the new, transformed document data. If the policy returns null, the document will be deleted instead of migrated.

myDatabase.addCollections({
  messages: {
    schema: messageSchemaV1,
    migrationStrategies: {
      // 1 means, this transforms data from version 0 to version 1
      1: function(oldDoc){
        oldDoc.time = new Date(oldDoc.time).getTime(); // string to unix
        return oldDoc;
      }
    }
  }
});

Asynchronous strategies can also be used:

myDatabase.addCollections({
  messages: {
    schema: messageSchemaV1,
    migrationStrategies: {
      1: function(oldDoc){
        oldDoc.time = new Date(oldDoc.time).getTime(); // string to unix
        return oldDoc;
      },
      /**
       * 2 means, this transforms data from version 1 to version 2
       * this returns a promise which resolves with the new document-data
       */
      2: function(oldDoc){
        // in the new schema (version: 2) we defined 'senderCountry' as required field (string)
        // so we must get the country of the message-sender from the server
        const coordinates = oldDoc.coordinates;
        return fetch('http://myserver.com/api/countryByCoordinates/'+coordinates+'/')
          .then(response => {
            const response = response.json();
            oldDoc.senderCountry=response;
            return oldDoc;
          });
      }
    }
  }
});

You can also filter the documents that should be migrated:

myDatabase.addCollections({
  messages: {
    schema: messageSchemaV1,
    migrationStrategies: {
      // 1 means, this transforms data from version 0 to version 1
      1: function(oldDoc){
        oldDoc.time = new Date(oldDoc.time).getTime(); // string to unix
        return oldDoc;
      },
      /**
       * this removes all documents older then 2017-02-12
       * they will not appear in the new collection
       */
      2: function(oldDoc){
        if(oldDoc.time < 1486940585) return null;
        else return oldDoc;
      }
    }
  }
}); 

—END—

Open source protocol: Apache-2.0 license

资源下载此资源为免费资源立即下载
Telegram:@John_Software

Disclaimer: This article is published by a third party and represents the views of the author only and has nothing to do with this website. This site does not make any guarantee or commitment to the authenticity, completeness and timeliness of this article and all or part of its content, please readers for reference only, and please verify the relevant content. The publication or republication of articles by this website for the purpose of conveying more information does not mean that it endorses its views or confirms its description, nor does it mean that this website is responsible for its authenticity.

Ictcoder Free Source Code RxDB (Reactive Database) is a powerful NoSQL database https://ictcoder.com/rxdb-reactive-database-is-a-powerful-nosql-database/

Share free open-source source code

Q&A
  • 1. Automatic: After making an online payment, click the (Download) link to download the source code; 2. Manual: Contact the seller or the official to check if the template is consistent. Then, place an order and make payment online. The seller ships the goods, and both parties inspect and confirm that there are no issues. ICTcoder will then settle the payment for the seller. Note: Please ensure to place your order and make payment through ICTcoder. If you do not place your order and make payment through ICTcoder, and the seller sends fake source code or encounters any issues, ICTcoder will not assist in resolving them, nor can we guarantee your funds!
View details
  • 1. Default transaction cycle for source code: The seller manually ships the goods within 1-3 days. The amount paid by the user will be held in escrow by ICTcoder until 7 days after the transaction is completed and both parties confirm that there are no issues. ICTcoder will then settle with the seller. In case of any disputes, ICTcoder will have staff to assist in handling until the dispute is resolved or a refund is made! If the buyer places an order and makes payment not through ICTcoder, any issues and disputes have nothing to do with ICTcoder, and ICTcoder will not be responsible for any liabilities!
View details
  • 1. ICTcoder will permanently archive the transaction process between both parties and snapshots of the traded goods to ensure the authenticity, validity, and security of the transaction! 2. ICTcoder cannot guarantee services such as "permanent package updates" and "permanent technical support" after the merchant's commitment. Buyers are advised to identify these services on their own. If necessary, they can contact ICTcoder for assistance; 3. When both website demonstration and image demonstration exist in the source code, and the text descriptions of the website and images are inconsistent, the text description of the image shall prevail as the basis for dispute resolution (excluding special statements or agreements); 4. If there is no statement such as "no legal basis for refund" or similar content, any indication on the product that "once sold, no refunds will be supported" or other similar declarations shall be deemed invalid; 5. Before the buyer places an order and makes payment, the transaction details agreed upon by both parties via WhatsApp or email can also serve as the basis for dispute resolution (in case of any inconsistency between the agreement and the description of the conflict, the agreement shall prevail); 6. Since chat records and email records can serve as the basis for dispute resolution, both parties should only communicate with each other through the contact information left on the system when contacting each other, in order to prevent the other party from denying their own commitments. 7. Although the probability of disputes is low, it is essential to retain important information such as chat records, text messages, and email records, in case a dispute arises, so that ICTcoder can intervene quickly.
View details
  • 1. As a third-party intermediary platform, ICTcoder solely protects transaction security and the rights and interests of both buyers and sellers based on the transaction contract (product description, agreed content before the transaction); 2. For online trading projects not on the ICTcoder platform, any consequences are unrelated to this platform; regardless of the reason why the seller requests an offline transaction, please contact the administrator to report.
View details

Related Source code

ICTcoder Customer Service

24-hour online professional services