Nodejs对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 请求工作没有问题。我错过了什么?

解决方法

用这种方式...

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

});
,

试试这个并确认您的用户模型中存在名为“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 });
      }
    });