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:
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
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.
If you want to keep the getting function to get user account separately then, you could try this.
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.
Consider the following:
Turn on your MongoDb locally.
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')
)probably your function with return
Promise { <pending> }
, itsbecause 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:
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.