Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

311
Visualizações
What is this error?: TypeError: Cannot read property '0' of undefined

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;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

http://www.passportjs.org/docs/login/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda