# Resolving MongoDB Error When Starting with Homebrew on macOS

## Introduction

While installing MongoDB Community Edition on my MacBook using Homebrew ([official MongoDB doc](https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/)), I encountered an issue: the `mongodb-community` service seemed to start successfully but was listed as **error** when I checked its status. If you're facing the same problem, here's a quick guide to help you fix it.

## The Issue

After running:

```bash
brew services start mongodb-community
```

I received a confirmation message. However, checking the service status with:

```bash
brew services list
```

showed:

```bash
Name              Status  User Plist
mongodb-community error
```

The MongoDB log (`/usr/local/var/log/mongodb/mongo.log`) contained warnings:

* **Running as root user**: `"You are running this process as the root user, which is not recommended"`
    
* **Termination signal received**: `"Received signal","attr":{"signal":15,"error":"Terminated: 15"}}`
    

These indicated that MongoDB was running as the root user, which can cause permission issues and lead to the service being stopped.

## The Solution

The main issue was incorrect ownership of the MongoDB data and log directories. Here's how to fix it:

### Steps:

1. **Stop the MongoDB Service**:
    
    ```bash
    brew services stop mongodb-community
    ```
    
2. **Terminate Any Running MongoDB Processes**:
    
    ```bash
    pkill -f mongod
    ```
    
3. **Change Ownership of MongoDB Directories**:
    
    ```bash
    sudo chown -R $(whoami) /usr/local/var/mongodb
    sudo chown -R $(whoami) /usr/local/var/log/mongodb
    ```
    
4. **Verify Directory Ownership**:
    
    ```bash
    ls -ld /usr/local/var/mongodb
    ls -ld /usr/local/var/log/mongodb
    ```
    
    Ensure your username is listed as the owner.
    
5. **Start the MongoDB Service as Your User**:
    
    ```bash
    brew services start mongodb-community
    ```
    
6. **Check the Service Status**:
    
    ```bash
    brew services list
    ```
    
    The service should now show as **started** under your username.
    
7. **Test the MongoDB Connection**:
    
    ```bash
    mongosh
    ```
    
    You should successfully connect to the MongoDB shell.
    

## Conclusion

By correcting the directory permissions and ensuring MongoDB runs under your user account (not as root), you can resolve the error when starting the `mongodb-community` service with Homebrew on macOS. Remember to avoid using `sudo` with `brew` commands to prevent permission conflicts.
