7

Case
How to open an existing database?

Issue
I already create one database with RxDB.create(), and created some collections, put some documents in it So, in another script, i want to open that database to execute some queries, but I don't know how to do it. I tried to use RxDB.create() with same database name, but it create new database and override the created database above.

Code sample

 const database = await createRxDatabase({
    name: path.join(app.getPath('userData') + '/db'),
    adapter: leveldown, // the full leveldown-module
    multiInstance: false,
  });

I just don't see appropriate way to check if .ldb file exists and how to get reference to rxdb database object without creating a new one.

Info
Environment: Electron
Adapter: LevelDB
Stack: React
Packages: "rxdb": "9.5.0", "leveldown": "5.6.0", "pouchdb-adapter-leveldb": "7.2.2"

Andon Mitev
  • 1,354
  • 1
  • 11
  • 30
  • This error happened to me because for some reason I was calling this piece of code several times in my app. Are you sure you are calling this only once? – Batato Oct 04 '21 at 09:57

1 Answers1

0

too late, but worth sharing because too few references about rxdb

found a workaround for react-native (iOS/Android) (rxdb 11.6.0)

works great for me and the data is still persistent

// database instance to be used throughout the runtime
let rxDB: RxDatabase<AppCollections>;

async function createRxDatabaseAsync() {
  // re-create RxDatabase by using the function below 
  // does not override existing data
  rxDB = await createRxDatabase<AppCollections>({
    name: 'mydatabase',
    storage: getRxStoragePouch('react-native-sqlite'),
    ignoreDuplicate: false,
  });
}

export async function initRxDatabaseAsync() {
  if (!rxDB) {
    await createRxDatabaseAsync();
  }

  // make sure we add the collection(s) only one time
  // my case is 'word' collection
  if (!rxDB.word) {
    await rxDB.addCollections({
      word: {
        schema: wordSchema,
      },
    });
  }
  return rxDB;
}

Lenam
  • 111
  • 1
  • 2
  • 9