No data added to MongoDB database collection on POST request through Postman

24 Views Asked by At

I'm building a server-side code to emulate a signup/signin page. If a user tries signing up with a registered email/username, or tries to sign in with an unregistered username, a 403 will be thrown at them. When a new user signs up, a JWT is sent from the server.

const express = require("express");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const jwtPassword = "123456";
const app = express();
app.use(express.json());

mongoose.connect(
      "mongodb+srv://username:[email protected]/";
);

const User = mongoose.model("User", {
    name: String,
    username: String,
    password: String,
});

async function userExists(username, password) {
    await User.findOne({email: username})
}

app.post("/signup", async function(req,res){
    const username = req.body.username;
    const password = req.body.password;
    const name = req.body.name;
    if (userExists(username, password)) {
        return res.status(403).json({
            msg: "User exists in our in memory db",
        });
    }
    const newUser = new User({
        email: username,
        password: password,
        name: name
    })
    User.save({newUser}).then(() => console.log("added new User to db"))
})

app.post("/signin", async function (req, res) {
    const username = req.body.username;
    const password = req.body.password;
    if (!userExists(username, password)) {
        return res.status(403).json({
            msg: "User doesn't exist in our in memory db",
        });
    }

    let token = jwt.sign({ username: username }, password);
    return res.json({
        token
    });
});

app.listen(3000, ()=>{console.log("server running on port 3000")});


When I send POST requests on the /signup route, the response is always the same Token for all combinations of usernames and passwords. When I send POST requests on the /signin route, the response is always that there's no registered user in the database, even when I enter correct details.

In the /signin problem is because of using jwtPassword instead of password, different tokens are generated for the same user instead of the 403 message. Converting the userExists() function into an asynchronous one is not helping either.

I tried using this solution by replacing the last line in the /signup post request but to no avail

User.create({newUser}).then(() => console.log("added new User to db"))
0

There are 0 best solutions below