Implement the Create User Service

Create src/services/user.service.js.

The service layer contains business logic and database operations.

The createUser function will accept validated user information and create a MongoDB document.

We will initially implement the basic creation logic. Password hashing will be integrated when authentication is implemented.

src/services/user.service.js
import { User } from '../models/user.model.js';

export async function createUser(userData) {
  const user = await User.create(userData);

  return user;
}

Creates a user document using the Mongoose model and returns the created document.

Key Takeaways
  • Services contain business logic.

  • User.create() creates and saves a MongoDB document.

  • Database operations should not be scattered throughout route definitions.