【问题标题】:What is this error?: TypeError: Cannot read property '0' of undefined这是什么错误?:TypeError:无法读取未定义的属性“0”
【发布时间】:2021-11-07 00:01:24
【问题描述】:

在尝试使用 mongodb 和 express 构建用户身份验证时,我遇到了一个错误。每次我在网站上单击提交时,基本上都会发生该错误。这是第一个问题,第二个问题是在我单击提交后,页面一直在加载,并且永远不会改变,就好像它卡在或陷入无限循环一样。我尝试删除数据库中的所有内容并重新开始,但这没有用。一点建议将不胜感激。

错误:

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;

【问题讨论】:

  • 错误可能在这一行results.ops[0]
  • 我相信,但我该怎么办? @depperm
  • 这取决于你想要做什么。添加对results.op[0] 的检查或完全省略?
  • 这取决于你。错误告诉你 results.ops 未定义。
  • @depperm 我刚刚检查了数据库,结果发现所有日志都完成了,所以我相信它可以工作,但我仍然收到该错误,并且页面只是继续加载而没有去任何地方。我不确定你所说的省略是什么意思,但我不相信我正在检查任何东西..我正在关注教程 btw

标签: javascript node.js mongodb authentication


【解决方案1】:

我当然不知道你想做什么,因为我不太擅长 mongodb,但我在护照 js 文档和 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/

【讨论】:

    猜你喜欢
    • 2023-02-26
    • 2019-09-02
    • 2019-01-15
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多