如何解决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 });
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。