MongoDB App Testing with Postman

MongoDB App Testing with Postman

Back in the day, MongoDB had the Data API feature, which allowed users to connect API testing tools such as Postman directly. It would generate an API key and an endpoint; you would then add them to Postman, and you would be connected to your database. Since last year, MongoDB hasn’t had that feature available.

My initial idea was to set up a test of a Registration/Login app where, basically, Cypress would update certain data to the database from the front end side. it would involve creating a new user, changing the user’s password, deleting the items, and so on. After that, Postman would run to retrieve this data that Cypress previously did on the front end. Now, my initial idea was to connect Postman directly to MongoDB in order to retrieve data. Since that feature isn’t available anymore, I had to choose another approach, which is, of course, totally legit.

You may find the Registration/Login App here:
https://account-manager-app-express-mong-production.up.railway.app/

If you are curious about the full source code, you should check out the GitHub repository:
https://github.com/NoToolsNoCraft/Account-Manager-App-Express-MongoDB

Understanding the App

This simple app is built using technologies such as NodeJS, JavaScript, a little bit of HTML and CSS, as well as Express, an important technology related to building your own servers (a widely used backend framework for Node.js.) It was necessary in order to connect to the database used, which is MongoDB in this case. After tested in local environment, the app was first pushed to GitHub and then deployed to Railway which is serving the app online (for free!).

What was necessary to make the app available for Postman testing?

In order to make the app available for Postman data retrieval, the index.js file (which contains the calls managing the communication between the application and the database) had to be updated with additional API calls.

In simple words, if you want to retrieve MongoDB data with Postman you must set up your own server through which you will manage to do that.

Click here to see all of the REST API-related calls that had to be updated (a part of the index.js file in the GitHub repository):
//The following parts of the code are for Postman testing

// Route to get all users from the login collection
app.get("/api/users", async (req, res) => {
    try {
        const users = await LogInCollection.find({});
        res.status(200).json(users);  // Return the users in JSON format
    } catch (error) {
        console.error("Error fetching users:", error);
        res.status(500).send("Error fetching users");
    }
});

// Route to add a new user
app.post("/api/users", async (req, res) => {
    try {
        const { name, password } = req.body;

        const existingUser = await LogInCollection.findOne({ name });

        if (existingUser) {
            return res.status(409).json({ message: "Username already exists. Please choose a different one." });
        }

        const newItem = new LogInCollection({ name, password });
        await newItem.save();

        res.status(201).json({ message: "User created successfully", newItem });
    } catch (error) {
        console.error("Error creating user:", error);
        res.status(500).json({ message: "Server error" });
    }
});



// Retrieve a Single User by Name
app.get("/api/users/:name", async (req, res) => {
    const userName = req.params.name;
    
    try {
        // Find the user by name
        const user = await LogInCollection.findOne({ name: userName });

        if (!user) {
            return res.status(404).send("User not found.");
        }

        res.status(200).json(user); // Send the user data back
    } catch (error) {
        console.error("Error fetching user:", error);
        res.status(500).send("Server error");
    }
});

// Update User Password by Name
app.put("/api/users/:name/password", async (req, res) => {
    const userName = req.params.name;
    const { newPassword } = req.body;

    if (!newPassword) {
        return res.status(400).send("New password is required.");
    }

    try {
        const result = await LogInCollection.updateOne(
            { name: userName },
            { $set: { password: newPassword } }
        );

        if (result.matchedCount === 0) {
            return res.status(404).send("User not found.");
        }

        res.status(200).send("Password updated successfully.");
    } catch (error) {
        console.error("Error updating password:", error);
        res.status(500).send("Server error");
    }
});


// Delete a Single User by Name
app.delete("/api/users/:name", async (req, res) => {
    const userName = req.params.name;

    try {
        // Find the user by name and delete it
        const result = await LogInCollection.deleteOne({ name: userName });

        if (result.deletedCount === 0) {
            return res.status(404).send("User not found.");
        }

        res.status(200).send("User deleted successfully.");
    } catch (error) {
        console.error("Error deleting user:", error);
        res.status(500).send("Server error");
    }
});

Requests types

Here is the list of actions we can make with this update:

  • Retrieve all items (all account usernames and passwords in the database)
  • Add a new single item (new account with username + password)
  • Retrieve a single item
  • Change the password of a single item
  • Delete a single item

Basically, this way, Postman can perform the same actions as the user can from the front end.

Lemme now explain each of these so that you can start using this Public API source yourself. Keep in mind that authorization isn’t needed for any of these requests.

Postman setup

Retrieve all items in the database (GET Request to Fetch Users)

Request: GET
Path: https://account-manager-app-express-mong-production.up.railway.app/api/users
Body: None

Expected result: You should get a response with the list of users stored in your MongoDB.

POST Request to Add a New User

Request: POST
Path: https://account-manager-app-express-mong-production.up.railway.app/api/users
Body (example):

{
  "name": "newUser",
  "password": "newPassword123"
}

Expected result: You should get a response saying "User created successfully".

Retrieve a single item

Request: GET
Path: https://account-manager-app-express-mong-production.up.railway.app/api/users/{username}
Replace {username} with the actual username of the user you want to retrieve.
Body: None
Expected result: You should receive the user data for the specified username.

Change the password value of a single item

Request: PUT
Path: https://account-manager-app-express-mong-production.up.railway.app/api/users/{username}/password
Replace {username} with the actual username whose password you want to update.
Body (example):

{
    "newPassword": "yourNewPassword"
}

Expected result: “Password updated successfully.”

If the user doesn’t exist, you’ll get: “User not found.”

Delete a Single Item (DELETE request)

Request: DELETE
Path: https://account-manager-app-express-mong-production.up.railway.app/api/users/{username}
Replace {username} with the actual username of the user you want to delete.
Body: None
Expected result: If the user is found, the response will be "User deleted successfully." If not, you’ll get a "User not found." message.

Additional info

Security Considerations

While this example doesn’t require authorization, it’s important to consider security concerns for production environments. Allowing unrestricted access to sensitive user data is risky and can lead to data breaches. To address this, developers should implement user authentication with technologies such as JSON Web Tokens (JWT) or OAuth. Additionally, HTTPS should be enforced to protect data in transit, and rate-limiting should be applied to prevent abuse of the API. Role-based access control (RBAC) can further ensure that only authorized users perform certain operations.

Future Improvements

There are several areas for future improvements to enhance the app’s functionality and security. One key addition would be user authentication, allowing only verified users to access or modify data. Adding validation rules for input data would help prevent database corruption or security vulnerabilities. Implementing rate-limiting would protect the API from excessive traffic or potential denial-of-service (DoS) attacks. Furthermore, improving the UI and documentation could make the app more user-friendly for both developers and testers.

Scroll to Top