UnhandledPromiseRejectionWarning:TypeError:无法读取null的属性“ _id”

时间:2020-03-15 22:45:26

标签: node.js express

收到此错误,我读了很多帖子,无济于事。
任何帮助将不胜感激,因为我一直在努力解决这一问题!

(node:2225) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2225) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

错误所指向的行。

at /Users/[redacted/Desktop/prod/track-server/src/routes/trackRoutes.js:11:53

有问题的代码。

const express = require('express');
const mongoose = require('mongoose');
const requireAuth = require('../middlewares/requireAuth');

const Track = mongoose.model('Track');
const router = express.Router();

router.use(requireAuth);

router.get('/tracks', async (req, res) => {
    const tracks = await Track.find({ userId: req.user._id });

    try {
        res.send(tracks);
    } catch (err) {
        res.status(422).send({ error: err.message });
    }
});

router.post('/tracks', async (req, res) => {
    const { name, locations } = req.body;

    if (!name || !locations) {
        return res.status(422).send({ error: 'You must provide a name and locations' });
    }

    try {
        const track = new Track({ name, locations, userId: req.user._id });
        await track.save();
        res.send(track);
    } catch (err) {
        res.status(422).send({ error: err.message });
    }
});

module.exports = router;

1 个答案:

答案 0 :(得分:0)

好吧,您在错误描述中有解释。由于某种原因,此代码req.user._id中的用户对象为null。您必须跟踪为什么它为null,以及是否将其正确附加到请求(猜测在requireAuth中间件中?)。