3

I use RxDB and want to update the document in it. This is how the db is created:

const _create = async function() {
  const db = await RxDB.create({
    name: 'myName',
    adapter: process.env.NODE_ENV === 'test' ? 'memory' : 'idb',
    password: process.env.DB_PASSWORD,
    multiInstance: true,
    ignoreDuplicate: true,
  });

  if (process.env.NODE_ENV === 'development') {
    window['db'] = db;
  }

  db.waitForLeadership().then(() => {});

  await Promise.all(collections.map(colData => db.collection(colData))).catch(
    e => e,
  );

  return db;
};

This is the method to get the db:

const getDB = () => {
  if (!dbPromise) dbPromise = _create();
  return dbPromise;
};

And this is the generator function to save data to DB:

export function* saveDataToDb(action) {
  const { key, value } = action;
  try {
    const db = yield getDB();

    const userDoc = yield db['my_collection'].find({ user: 'myUser' })
      .exec()
      .then(docs => docs[0]);

    const operationType = value ? '$set' : '$unset';

    const updatedDoc = yield userDoc
      .update({
        [operationType]: {
          [`unsavedData.${key}`]: value ? value.toJS() : '',
        },
      })
      .then(doc => doc);
    yield updatedDoc.save();
  } catch (error) {
    console.log(error);
  }
}

The issue is: usually saveDataToDb function works pretty good, but after calling it several times, it goes to catch with this error:

CustomPouchError: {
  docId: "myUser"
  error: true
  id: "myUser"
  message: "Document update conflict"
  name: "conflict"
  status: 409
}

It happens when I'm trying to yield userDoc.update. I know that this issue could happen because of different _rev properties in original and updated documents after update.then(), but redefining the value of _rev in updated document does not help! I also have found this solution for PouchDB: https://github.com/pouchdb/pouchdb/issues/1691#issuecomment-38112213 Since I'm new in RxDB, please pinpoint what should I do regarding to RxDB document.update! Thanks in advance.

UPD: I tried to use atomicUpdate this way:

const changedData = oldDoc => {
  const val = value ? value.toJS() : '';
  oldDoc.unsavedData[key] = val;
  return oldDoc;
};

const updatedDoc = yield userDoc.atomicUpdate(changedData).then(doc => doc);
yield updatedDoc.save();

But data is not updated in the database. Perhaps, I'm doing it in the wrong way? How should I use atomicUpdate regarding to update method in the code above?

4

1 回答 1

3

RxDocument 方法atomicUpdate可能是您需要的,以避免同时运行多个更新引起的冲突。

于 2019-04-05T15:52:40.030 回答