diff --git a/packages/server/src/api/controllers/model.js b/packages/server/src/api/controllers/model.js index 74e3494eba..d9277c2f3d 100644 --- a/packages/server/src/api/controllers/model.js +++ b/packages/server/src/api/controllers/model.js @@ -33,6 +33,7 @@ exports.save = async function(ctx) { views: {}, ...rest, } + let renameDocs = [] // if the model obj had an _id then it will have been retrieved const oldModel = ctx.preExisting @@ -49,14 +50,11 @@ exports.save = async function(ctx) { include_docs: true, }) ) - - const docs = records.rows.map(({ doc }) => { + renameDocs = records.rows.map(({ doc }) => { doc[_rename.updated] = doc[_rename.old] delete doc[_rename.old] return doc }) - - await db.bulkDocs(docs) delete modelToSave._rename } @@ -69,9 +67,6 @@ exports.save = async function(ctx) { modelView.schema = modelToSave.schema } - const result = await db.post(modelToSave) - modelToSave._rev = result.rev - // update linked records await linkRecords.updateLinks({ instanceId, @@ -82,6 +77,14 @@ exports.save = async function(ctx) { oldModel: oldModel, }) + // don't perform any updates until relationships have been + // checked by the updateLinks function + if (renameDocs.length !== 0) { + await db.bulkDocs(renameDocs) + } + const result = await db.post(modelToSave) + modelToSave._rev = result.rev + ctx.eventEmitter && ctx.eventEmitter.emitModel(`model:save`, instanceId, modelToSave) diff --git a/packages/server/src/db/linkedRecords/LinkController.js b/packages/server/src/db/linkedRecords/LinkController.js index b006e798c2..fc28320d70 100644 --- a/packages/server/src/db/linkedRecords/LinkController.js +++ b/packages/server/src/db/linkedRecords/LinkController.js @@ -161,7 +161,7 @@ class LinkController { }) // now add the docs to be deleted to the bulk operation operations.push(...toDeleteDocs) - // replace this field with a simple entry to denote there are links + // remove the field from this row, link doc will be added to record on way out delete record[fieldName] } }