javascript – CouchDB best practices for updating related documents

Question:

I'm using CouchDB and NodeJs with these sample documents.

Role {
  _id,
  name
}

User {
  _id,
  email,
  password,
  role: {
    _id,
    name
  }
}

What is the best practice for when I update a Role , also update it inside User if the _id of the Roles are the same.

This is just an example, in the application there will be cases of duplicated documents in different parts of the bank, requiring this type of update to avoid inconsistencies.

Answer:

Couchdb is a little different from relational databases, so the way we build applications changes a little too. Responding to your case, what I do is create a "roles" model in the backend node and another "user". Afterwards, whenever a new user is created, it will be saved in the BD couch as a json document and will have a role object. If that user is later updated, in couchdb, this will be a new document with a new _rev, ie to save this update you will have to pass the entire document, and at that point if the roles have also changed, they will be updated . If you need to maintain compatibility with previous roles, you can include a "version" parameter in the role object.

Example:

{
_id: "someUser",
"doc_type": "user",
"name": "his name",
"role": {
  "Version": 1,
  "description": "admin"
}
}
Scroll to Top
AllEscort