While trying to build user authentification using mongodb and express I came across an error. The error basically happens every time I click submit on the website. That's the first problem, the second is after I click submit the page just keeps loading and never changes as if its stuck or trapped in an infinite loop. I tried deleting everything in the database and starting over but that didn't work. A little advice would be appreciated.
The error:
app: authRouter {
app: authRouter acknowledged: true,
app: authRouter insertedId: new ObjectId("613b5afd2139aeac87bd9682")
app: authRouter } +0ms
app: authRouter TypeError: Cannot read property '0' of undefined
app: authRouter at addUser (C:\Users\Yanki XXIV\Desktop\pluralsight\src\routers\authRouter.js:24:30)
app: authRouter at processTicksAndRejections (internal/process/task_queues.js:95:5) +19ms
authRouter.js:
const express = require('express');
const debug = require('debug')('app: authRouter');
const { MongoClient } = require('mongodb');
const authRouter = express.Router();
authRouter.route('/signUp').post((req, res) => {
const {username, password} = req.body;
const url =
'mongodb+srv://Yoshi:Yumcmaster1@cluster0.atic5.mongodb.net?retryWrites=true&w=majority'
const dbName = 'testdb';
(async function addUser(){
let client
try {
let client = await MongoClient.connect(url);
const db = client.db(dbName);
const user = {username, password};
const results = await db.collection('users').insertOne(user);
debug(results);
req.login(results.ops[0], ()=> {
res.redirect('/auth/profile');
});
} catch (error) {
debug(error)
}
client.close();
}());
});
authRouter.route('/profile').get((req, res) => {
res.json(req.user);
})
module.exports = authRouter;
I certainly don't know what your trying to do because I'm not so good at mongodb but I found a rather intresting thing in passport js docs and stackoverflow
Note: passport.authenticate() middleware invokes req.login() automatically. This function is primarily used when users sign up, during which req.login() can be invoked to automatically log in the newly registered user.
Check version of MongoDB Node.js Driver with command npm list mongodb. If it is version 4 then you can not access result.ops. In version 4 insertOne returns insertOneResult that have only 2 properties: acknowledged and insertedId.
NodeJS + MongoDB: insertOne() - get the inserted document from result.ops