Skip to content

Replace .save() calls with UserRoleModel.create() where applicable #137

Description

@sanjaysah101

Background:

Currently, code uses .save() to persist new UserRole documents. However, UserRoleModel.create(...) both creates and saves in one step, returning a promise that resolves to the saved document. Using create() is more concise and avoids redundancy (creating document + explicit save).

Goal:
Refactor code to use UserRoleModel.create() instead of:

const ur = new UserRoleModel({...});
await ur.save();

Directly return the result of UserRoleModel.create() instead.


Tasks

  1. Find all .save() usages:

    • Search across the user-service repo for .save() invocations related to UserRoleModel.
    • Identify cases where .save() is used after new UserRoleModel(...) or otherwise where create() could replace the pattern.
  2. Replace with .create():

    • For simple one-liner document creation, refactor to:

      const userRole = await UserRoleModel.create({ /* fields */ });
      return userRole;
    • Remove redundant new UserRoleModel(...) + .save() patterns.

  3. ⚠️ Considerations (when not to replace):

    • If extra logic is applied to the document before saving:

      const userRole = new UserRoleModel(data);
      userRole.token = generateToken();
      await userRole.save();

      → keep .save() in such cases.

    • If you rely on special middleware or hooks that behave differently between .create() and .save(), verify carefully before replacing.

  4. Test and ensure behavior is unchanged:

    • Run unit/integration tests covering UserRole creation to make sure no regressions.
    • Validate that required hooks/middleware still trigger as expected.
  5. Code review & consistency:

    • Ensure style is consistent (error handling, await usage, promise returns).
    • Update comments/documentation if any reference .save().

Acceptance Criteria

  • All safe instances of .save() (where only saving a new UserRoleModel document) are replaced with UserRoleModel.create(...).
  • .save() remains in cases where additional field manipulation or middleware dependency requires it.
  • All tests pass with no regressions.
  • Code review feedback incorporated.

Metadata

Metadata

Fields

No fields configured for Feature.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions