Nodejs对mongoDB的GET请求返回未定义

时间:2021-04-28 11:04:14

标签: node.js reactjs mongodb get

后台

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 执行请求,它返回 undefined。 DB 已连接,POST 请求工作没有问题。我错过了什么?

2 个答案:

答案 0 :(得分:0)

用这种方式...

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

});

答案 1 :(得分:-1)

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

    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 });
      }
    });
相关问题