【问题标题】:Nodejs GET request to mongoDB returns undefined对 mongoDB 的 Nodejs GET 请求返回未定义
【发布时间】:2021-04-28 11:04:14
【问题描述】:

后台

const GetUsersRoute = express.Router();
const GetContactUsers = require('./DB/GetContactUsers');

app.get('/fetchContactUsers', (req, res) => {
    GetContactUsers.find({}, (err, user) => { 
        if (err) {
            console.log(err);
            res.json(err);
        } else {
            console.log(user.data);
            res.json(user.data);
        }
    });
});

./DB/GetContactUsers

const mongoose = require('mongoose');
const GetContactUsers = mongoose.Schema({
    name: String,
    email: String,
    message: String
});
module.exports = mongoose.model('GetContactUsers', GetContactUsers);

我正在通过 Postman 发出请求,但它返回未定义。数据库已连接,POST 请求工作没有问题。我错过了什么?

【问题讨论】:

  • console.log(user); 它是记录数组。你可以做user[0].data
  • 返回“无法读取未定义的属性‘数据’”
  • console.log(user) 打印什么?
  • 返回一个空数组
  • 数据库中没有记录。

标签: node.js reactjs mongodb get


【解决方案1】:

这样用……

GetContactUsers.find({}.then(function (doc) {
  // use doc
}).catch(ex){

});

【讨论】:

    【解决方案2】:

    试试这个并确认你的用户模型中存在名为“数据”的对象

        app.get('/fetchContactUsers', async (req, res) => {
          try {
            const allContactUsers = await GetContactUsers.find();
            console.log(allContactUsers);     //chech if User have Object Data
            res.status(201).json(allContactUsers.data);  //if still undefined than there may be no object with "DATA"
          } catch (error) {
            res.status(404).json({ message: error.message });
          }
        });
    

    【讨论】:

    • 感谢您的回答。它返回一个空数组。我应该改变什么?
    • 如果为空,则首先需要在数据库中添加数据,然后再获取该数据。如果有帮助,也将答案标记为“勾选”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2021-01-28
    • 1970-01-01
    • 2017-02-01
    • 2018-03-22
    • 2018-06-04
    • 2020-03-03
    相关资源
    最近更新 更多