Saloni Sikdar
Saloni Sikdar

Reputation: 1

<Model>.findOne() in mongoose, not working

This is my entire code. I have tried a lot of things still not working out. post request on postman shows a load and then crashes. there is no error message

    const express = require('express');
    const bcrypt = require('bcryptjs');
    const mongoose = require('mongoose');
    const app = express();

    app.use(express.json());

    // // Connection URL
    var MongoClient = require('mongodb').MongoClient;
    var db = "mongodb://localhost:27017/userDb";
    MongoClient.connect(db, { useNewUrlParser: true }, function (err, db) {
        if (err) throw err;
        console.log("Mongo DB Connected...!");
        //   db.close();
    });

// User Database

    const Schema = mongoose.Schema;
    const UserSchema = new Schema({
        username: {
            type: String,
            required: true,
            minlength: 5,
            maxlength: 50
        },
        password: {
            type: String,
            required: true,
            minlength: 5,
            maxlength: 1024
        },
        hash: {
            type: String,
            required: true,
            minlength: 5,
            maxlength: 1024
        },
    });
    var User = mongoose.model('User', UserSchema);

//Register New User

    app.post('/register', async (req, res) => {
        console.log('try registering : ', req.body);
        console.log(User);

// Check if this user already exisits

        console.log('in here');

//this is where its not working

        let user = await User.findOne({ username: req.body.username });
        if (user) {
            return res.status(400).send('That user already exisits!');
        }
        // Encrypt Password
        try {
            console.log('Encrypt');
            bcrypt.genSalt(10, (err, salt) => {
                bcrypt.hash(req.body.password, salt, (err, hash) => {
                    console.log('-----password:', hash, '& salt', salt, '-----');
                    passwordHash = hash;
                    saltHash = salt;
                    user = new User({
                        username: req.body.username,
                        password: passwordHash,
                        hash: saltHash,
                    });
                    console.log(user);
                    user.save();
                    res.send('Registered');
                });
            });
        } catch (err) {
            console.log(err);
        }
    });

Login User

    app.post('/login', async (req, res) => {
        console.log('try Login : ', req.body);
        let user = await User.findOne({ username: req.body.username });
        // console.log(user);
        if (!user) {
            return res.status(400).send('Incorrect username');
        }
        console.log(user);
        console.log('decrypting entered password');

Decrypt Password

        const passwordHash = await bcrypt.hash(req.body.password, user.hash);
        if (passwordHash == user.password) {
            // console.log("in")
            res.send('You are logged in!');
        } else {
            console.log('incorrect password');
        }

    });

I am creating my port here

    //PORT
    const port = process.env.PORT || 3020;
    app.listen(port, () => console.log(`listening on port ${port}...`));

Upvotes: 0

Views: 3028

Answers (2)

Prasanta Bose
Prasanta Bose

Reputation: 674

Here I have fixed your code. See here. link

There is something I'll like to point out.

  1. Use either mongoose or MongoClient. Try learning mongoose it's easier to code with mongoose.
  2. Always put your DB references or query executions inside try-catch.
  3. Return doesn't serve it's purpose inside try. Throw an error there.

That's all. Try to learn a better code structure. If there's some doubt let me know.

Upvotes: 0

Sunny Parekh
Sunny Parekh

Reputation: 983

You need to change the User.findOne to below-mentioned code:

let user = await User.findOne({ username: req.body.username }).exec();

Change this and let us know the outcome.

Upvotes: 2

Related Questions