I'm trying to bulk update some RxDB docs, since RxDB does not have a bulk update function I have to use the bulkDocs function on the built in pouchdb instance. I can successfully do this but then my revisions are out of sync. Is there a way to sync rxdb revisions with pouchdb when using the pouchdb instance?
My code:
async bulkUpdate(docs) {
let db = await ProjectDB.get();
let data = [];
let nodeDocs = await db.collections.nodes.find().exec();
_.each(docs, doc => {
let matchingDoc = _.find(nodeDocs, n => {return n.id === doc._id});
if (matchingDoc) {
data.push(_.omit(_.assign({_id: matchingDoc.id, _rev: matchingDoc.revision}, matchingDoc.toJSON(), doc), "id"));
}
});
await db.collections.nodes.pouch.bulkDocs({docs: data}, {force: true}).then(docs => {
_.each(docs, doc => {
console.log(doc);
})
})
}
Solution: need to emit a change event for the relevant rxdb documents to sync with.
I sourced some code from the rxdb repo and tweaked:
static async bulkUpdate(collection, docs) {
let db = await ProjectDB.get();
let docIds = _.map(docs, doc => {return doc.id});
let rxDocs = await collection.findByIds(docIds);
let updatedDocs = new Map();
let bulkUpdateDocs = [];
_.each(docs, doc => {
let matchingDoc = rxDocs.get(doc.id);
if (matchingDoc) {
bulkUpdateDocs.push(_.omit(_.assign({_id: matchingDoc.id, _rev: matchingDoc.revision}, matchingDoc.toJSON(), doc), "id"));
updatedDocs.set(doc.id, _.assign({_rev: matchingDoc.revision}, matchingDoc.toJSON(), doc))
}
});
let startTime, okResults;
const results = await db.lockedRun(async () => {
startTime = Date.now();
return await collection.pouch.bulkDocs({docs: bulkUpdateDocs});
});
const endTime = Date.now();
okResults = results.filter((r: any) => r.ok);
// for each updated doc a change event is emitted that the rxdb collection may subscribe to...
_.each(okResults, r => {
let originalDoc = rxDocs.get(r.id);
let updatedDoc = updatedDocs.get(r.id);
if (originalDoc) {
updatedDoc._rev = r.rev;
let changeEvent = new RxChangeEvent(
'UPDATE',
updatedDoc.id,
updatedDoc,
db.token,
collection.name,
false,
startTime,
endTime,
originalDoc._data,
originalDoc,
);
originalDoc.$emit(changeEvent);
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.