RxDB (Reactive Database) is a powerful NoSQL database

RxDB (Reactive Database) is a powerful NoSQL database

2022-10-28 0 1,526
Resource Number 47041 Last Updated 2025-02-21
¥ 0USD 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/kyym/rxdb-reactive-database-is-a-powerful-nosql-database.html

Share free open-source source code

Q&A
  • 1, automatic: after taking the photo, click the (download) link to download; 2. Manual: After taking the photo, contact the seller to issue it or contact the official to find the developer to ship.
View details
  • 1, the default transaction cycle of the source code: manual delivery of goods for 1-3 days, and the user payment amount will enter the platform guarantee until the completion of the transaction or 3-7 days can be issued, in case of disputes indefinitely extend the collection amount until the dispute is resolved or refunded!
View details
  • 1. Heptalon will permanently archive the process of trading between the two parties and the snapshots of the traded goods to ensure that the transaction is true, effective and safe! 2, Seven PAWS can not guarantee such as "permanent package update", "permanent technical support" and other similar transactions after the merchant commitment, please identify the buyer; 3, in the source code at the same time there is a website demonstration and picture demonstration, and the site is inconsistent with the diagram, the default according to the diagram as the dispute evaluation basis (except for special statements or agreement); 4, in the absence of "no legitimate basis for refund", the commodity written "once sold, no support for refund" and other similar statements, shall be deemed invalid; 5, before the shooting, the transaction content agreed by the two parties on QQ can also be the basis for dispute judgment (agreement and description of the conflict, the agreement shall prevail); 6, because the chat record can be used as the basis for dispute judgment, so when the two sides contact, only communicate with the other party on the QQ and mobile phone number left on the systemhere, in case the other party does not recognize self-commitment. 7, although the probability of disputes is very small, but be sure to retain such important information as chat records, mobile phone messages, etc., in case of disputes, it is convenient for seven PAWS to intervene in rapid processing.
View details
  • 1. As a third-party intermediary platform, Qichou protects the security of the transaction and the rights and interests of both buyers and sellers according to the transaction contract (commodity description, content agreed before the transaction); 2, non-platform online trading projects, any consequences have nothing to do with mutual site; No matter the seller for any reason to require offline transactions, please contact the management report.
View details

Related Article

make a comment
No comments available at the moment
Official customer service team

To solve your worries - 24 hours online professional service