使用 GET 定义了相同的常量,但使用 POST 未定义 - express、mongo、react

Same constant is defined with GET but undefined with POST - express, mongo, react

我正在学习 React 教程,其中我正在使用 MERN 堆栈构建一个基本博客。

在这种特殊情况下,在我的 Server.js 文件中,我正在尝试向 MongoDB 发出 POST 请求。它使用 URL 参数识别集合 & JSON 对象,改变对象 & returns 一个等于新对象的新常量。

问题是等于找到的对象的 const 显示未定义。但是,我无法弄清楚为什么会这样。使用具有相同 constGET 请求的另一个函数(每个函数都是各自函数的本地函数)按设计工作,没有关于定义 const.

的错误

import express from 'express';
import bodyParser from 'body-parser';
import { MongoClient } from 'mongodb';

const app = express();

// also tried to use express' built in bodyparser, same error
app.use(bodyParser.json());

// working GET req function using the same const
app.get('/api/articles/:name', async (req,res) => {
    try {
        const articleName = req.params.name;

        const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
        const db = client.db('my-app-db');

// this is the const in question, equal to object found
// based on name param passed in URL
        const articleInfo = await db.collection('articles').findOne({ name: articleName });
        res.status(200).json(articleInfo);

        console.log(articleInfo);

        client.close();
    } catch (error) {
        res.status(500).json({message: 'Error connecting to db', error});
    }
    
});

// non working POST req function, using the same const
// added slash to front of path as it was originally missing, still 
// getting error
app.post('/api/articles/:name/upvote', async (req,res) => {
    try {
        const articleName = req.params.name;

        const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
        const db = client.db('my-app-db');
        
        // gets error for being undefined at Server.js 32:5
        const articleInfo = await db.collection('articles').findOne({ name: articleName });
        await db.collection('articles').updateOne({ name: articleName },{
            '$set' : {
                upvotes: articleInfo.upvotes + 1,
            }, 
        });
        
        // this is updated article sent as response 
        const updatedArticleInfo = await db.collection('articles').findOne({ name: articleName });

        res.status(200).json(updatedArticleInfo);
        client.close();

    } catch (error) {
        res.status(500).json({message: 'Error connecting to db', error});
    }
})

app.listen(8000, () => console.log('Listening on port 8000'));

这个错误与在 Postman 中收到的完全一样

ReferenceError: articleInfo is not defined

at C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\src/Server.js:32:5

at Layer.handle [as handle_request] (C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\node_modules\express\lib\router\layer.js:95:5)

at next (C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\node_modules\express\lib\router\route.js:137:13)

at Route.dispatch (C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\node_modules\express\lib\router\route.js:112:3)

at Layer.handle [as handle_request] (C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\node_modules\express\lib\router\layer.js:95:5)

at C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\node_modules\express\lib\router\index.js:281:22

at param (C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\node_modules\express\lib\router\index.js:354:14)

at param (C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\node_modules\express\lib\router\index.js:365:14)

at Function.process_params (C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\node_modules\express\lib\router\index.js:410:3)

at next (C:\Users\oduboise\Desktop\sandbox\react-full-stack\my-app-backend\node_modules\express\lib\router\index.js:275:10)

这是成功的 GET 请求的响应,作为 JSON 对象

{
"_id": "5ec60f1390d2ce923cdb0e41",
"name": "what-react",
"upvotes": 0,
"comments": []
}

这也是我第一次在 Whosebug 上提问,一般我都能算出来out/find。因此,任何问题格式提示也将不胜感激

检查文章是否存在,通过添加 if 条件来避免 "undefined" 错误

const articleInfo = await db.collection('articles').findOne({ name: articleName });
console.log('articleInfo ===>',articleInfo);
if(articleInfo){

            console.log('article upvotes==',articleInfo.upvotes);

            await db.collection('articles').updateOne({ name: articleName },{
                    '$set' : {
                        upvotes: articleInfo.upvotes + 1,
                   }, 
            });
}else{
   res.status(404).json({message:"Article not found"});
}