Lasse Jonassen
Lasse Jonassen

Reputation: 23

Response from mongodb either returns null or can't find specific document

I am building a login system, and i have ran into some issues, that i cannot figure out how to solve. I have tried some different options with find() and findOne() but either does not work in my case. Under here is the first solution i have tried to solve the issue.

router.post('/', async (req, res) => {
    try {
        const user = await User.find(User.username = req.body.user);
        if (req.body.pass == user.password)
            res.send('Login');
        else
            res.send('Passwords don\'t match');
    } catch {
        res.send('User Not Found');
    }
});

This solution returns the catch response: User Not Found.

This is the second solution i have tried:

router.post('/', async (req, res) => {
    try {
        const user = await User.find(User => User.username = req.body.user);
        if (req.body.pass == user.password)
            res.send('Login');
        else
            res.send('Passwords don\'t match');
    } catch {
        res.send('User Not Found');
    }
});

This solutions returns: Cannot set property 'username' of null.

I both cases i am sending this request: {"user": "Lasse", "pass": "LasseMJ"} which is a user that i know exists in my database.

This is my Mongoose Schema:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    username: {type: String, required: true},
    password: {type: String, required: true}
});

module.exports = mongoose.model('Users', userSchema);

This is my server.js

const express = require('express');
const bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const userRoutes = require('./routes/users');
const loginRoutes = require('./routes/login');

if (process.env.NODE_ENV != 'production') {
    require('dotenv').config();
}

const app = express();
app.use(express.json());

app.use('/users', userRoutes);
app.use('/login', loginRoutes);


mongoose.connect(process.env.DB_CONNECTION, {
    useNewUrlParser: true,
    useUnifiedTopology: true 
 });
 const db = mongoose.connection;
 db.on('error', error => console.error(error));
 db.once('open', () => console.log('Connected to db'));

app.listen(3001);

Upvotes: 0

Views: 171

Answers (1)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

AFAIK, the find method receives a condition to search for documents as a JSON object. To search for a user by username, the syntax should be :

     const user = await User.find({username : req.body.user});

Notice, the find method will return an array instead of an object, we can use findOne to get the user object, like so :

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

And in this case, username should be unique in the collection.

You can find more information from Mongoose official document here

Upvotes: 1

Related Questions