邮差返回一个空回复



我正在将我的应用程序的后端连接到mongodb,当我用poster进行测试时,它返回一个空体-我不知道发生了什么。数据库已成功连接。

我已经编码了一个包含5个条目的模型,如下所示,还有app.js文件(也在下面(。我已经把路由放在了app.js文件中,以便使其更加清晰。我已经仔细检查过了,我已经导出了所有内容,但我不知道出了什么问题。我以同样的方式对其他react应用程序的后端进行了编码,邮递员一直工作得很好。

此外,我的邮递员设置有";内容类型";设置为application/json,其他一切都未选中。

app.js:

const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const bodyParser = require('body-parser')
const router = require('express').Router();
const DiaryEntry = require('./models/diaryEntry')
require('dotenv').config()
//App
const app = express()
//database
mongoose.connect(process.env.ATLAS_URI, {
useNewUrlParser: true,
}).then(() => console.log("Database Connected"))

//middlewares
app.use(bodyParser.json())
app.use(cors())
router.route("/").get((req, res) => {
DiaryEntry.find()
.then(diaryEntries => res.json(diaryEntries))
.catch(err => res.status(400).json('Error: ' + err));
});

const port = process.env.PORT || 5000 //default PORT
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})

模式(模型(:

const mongoose = require('mongoose')
const diaryEntrySchema = new mongoose.Schema({
mood: {
type: Number,
required: true
},
date: {
type: Date,
required: false
},
entry1: {
type: String,
required: false,
trim: true
},
entry2: {
type: String,
required: false,
trim: true
},
entry3: {
type: String,
required: false,
trim: true
}
}, {timestamps: true}
);
const DiaryEntry = mongoose.model('DiaryEntry', diaryEntrySchema);
module.exports = DiaryEntry;

最后,向json发布请求(get请求也不起作用(:

{
"mood": 8,
"entry1": "hey",
"entry2": "test",
"entry3": "whats up"
}

根据mongoose文档,`.find((接受一个arg,它可以是一个空的obj来查找集合中的所有条目。

例如:

MyModel.find({}).then(data => do something with data);

使用此

DiaryEntry.find().exec() .then(diaryEntries => res.json(diaryEntries)) .catch(err => res.status(400).json('Error: ' + err)); });

在猫鼬中的find和findOne方法之后,您应该使用exec()

最新更新