So I am trying to enter a post using postman into a mongo db server but my post just returns empty. When I look into my server nothing has been entered and there is no error
table:
const mongoose = require('mongoose');
//Schema describes how our data looks
const PostSchema = mongoose.Schema({
fullName: {
type: String,
required: true,
},
date_created: {
type: Date,
default: Date.now
},
id: {
type: Number,
required: true
}
});
module.exports = mongoose.model('customer', PostSchema);
Route file
const express = require('express');
const router = express.Router();
const customer = require('../models/customer')
router.post('/', async (req,res) => {
const post = new customer({
fullName: req.body.fullName,
id: req.body.id
});
try{
const savedCust = await customer.save();
res.json(savedCust);
} catch (err) {
res.json({message: err});
}
});
module.exports = router;
This is what I submit on postman:
{
"fullName" : "Joy Robinson",
"id": 2397
}
And this is the response that I get back:
{
"message": {}
}
CodePudding user response:
The error said that customer.save()
isn't a function. This happened in your try {...}
block inside your route file. The reason for that is that it's not a function. You should be doing post.save()
:
// route file
const express = require('express');
const router = express.Router();
const customer = require('../models/customer');
router.post('/', async (req,res) => {
const post = new customer({
fullName: req.body.fullName,
id: req.body.id
});
try {
const savedCust = await post.save(); // right here
res.json(savedCust);
} catch (err) {
res.json({message: err});
}
});
module.exports = router;