Home > OS >  Why can't i fetch data from my database in mongodb nodejs?
Why can't i fetch data from my database in mongodb nodejs?

Time:06-17

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:\Users\isaia\programing\stinkysocks\chat\script.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.

CodePudding user response:

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 ?

CodePudding user response:

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.

  • Related