skip to Main Content

I’m trying to make a simple login system with mongodb.
Connecting works fine, but when i try to get the password:

async function getAdminPassword(username) {
    const query = { username: username }

    // console.log(admins)
    const user = await admins.findOne(query);

    try {
        return user.password
    }
    catch (err) {
        console.log(err);
    }

}

It will give this error:

TypeError: Cannot read property 'password' of null
    at getAdminPassword (C:Usersisaiaprogramingstinkysockschatscript.js:44:21)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

Here is my database, in case anyone wants it:
a part of my database

Why doesn’t this work? Thanks in advance!

By the way, this is just a test. Please don’t tell me to hash my passwords, i know i should.

2

Answers


  1. I can’t really say much since the source code you provided are bunch of snippets here and there.

    But looking at the error, it means the model you are querying for using username, it is null which means either the value for username is not defined or the username cannot be found in the collection.

    What do you get when reading the value of req.body.username ?

    UPDATE

    This is just an example of how you could adapt to your code. I am not sure how you get the request but you can refer to mine here.

    const Admin = require('../models/admins'); // This is import the model
    
    exports.getAdminAccount = (req, res, next) => {
        const adminUserAccount = req.body.username;
        Admin.findOne({username: adminUserAccount})
            .then(adminUser => {
                // you can do your login functions here
                });
            })
            .catch(err => {
                // you can do your login functions here for error
            });
    };
    

    If you want to keep the getting function to get user account separately then, you could try this.

    const Admin = require('../models/admins'); // This is import the model
    
    async function getAdminPassword(username){
    
        const adminAccount = await Admin.findOne({username: username});
        if(!adminAccount){
            // your logic here if not account exist
            return;
        }
    
        //your logic here if account exists
        const adminPassword = adminAccount.password;
        return adminPassword;
    }
    

    If it’s still not working, like I mentioned you can console log username that you are passing to the function and see what you get. Then check if the username exists in the collection.

    I suspect the username you are passing is somehow incorrect.

    Apart from that, please hash your password when saving in db.

    Login or Signup to reply.
  2. Consider the following:
    Turn on your MongoDb locally.

    1. make sure your application is connected to db/ the username you are
      looking for exist in your DB.( Do not forget to import the schema you are using const admins= require('./models/yourAdminsModelJs'))

    2. probably your function with return Promise { <pending> }, its
      because promise will always log pending as long as its results are
      not resolved yet. You must call .then on the promise to capture the
      results regardless of the promise state (resolved or still pending)

    your full code:

    const admins = require('./models/adminsModelJs')
    ..
    ..
    ..
    async function getAdminPassword(username) {
        const query = { username: username }
        // console.log(admins)
        const user = await admins.findOne(query);
        // console.log(user)
        try {
            // console.log(user.password)
            return user.password
        }
        catch (err) {
            console.log(err);
        }
    }
    
    const result = getAdminPassword("someExample")
    console.log(result)
    
    result.then(function (result) {
        console.log(result) // "someExample password"
    })
    

    I am a litle bit suspicious about the way you are saving the password, consider using encryption algorithm.

    Do not forget to set to username unique : true when creating the Schema.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search