Reputation: 43
I am working on connecting the backend of my app to mongodb and when I test with postman, it returns an empty body - I have no idea what is going on. The database is successfully connected.
I have coded a model with 5 entries as seen below and also have the app.js file (also below). I have put the route in the app.js file in order to make it more clear. I have double checked and I have exported everything but I have no idea what is going wrong. I have coded backend of other react apps in the same way, and the postman has always worked perfectly.
Also, my postman settings has "Content-Type" set to application/json and everything else is unchecked.
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}`)
})
Schema (Model):
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;
And finally, the post request to json (get request doesnt work either):
{
"mood": 8,
"entry1": "hey",
"entry2": "test",
"entry3": "whats up"
}
Upvotes: 0
Views: 2390
Reputation: 45
use this
DiaryEntry.find().exec() .then(diaryEntries => res.json(diaryEntries)) .catch(err => res.status(400).json('Error: ' + err)); });
after find and findOne method in mongoose you should use exec()
Upvotes: 0