Reputation: 469
sending form data to mongodb with mongoose and express - the document is created with an id but the form data does not get sent
the schema
const reportSchema = mongoose.Schema({
project: [
{
studio: String,
code: String,
name: String
}
],
},
{
collection: 'reports'
}
);
module.exports = mongoose.model('Report', reportSchema);
and the route
app.post("/", (req, res) => {
const report = new Report({
project: {
studio: req.body.studio,
code: req.body.code,
name: req.body.name
}
});
report.save(err => {
if (err) return res.status(404).send({ message: err.message });
return res.send({ report });
});
sending a post request in postman creates a document with an empty array.
The post looks like
{
"project": {
"studio": "main",
"code": "411",
"name": "some project"
}
}
thanks for any help
updating the route to
app.post("/", (req, res) => {
const report = new Report({
project: {
studio: req.body.project.studio,
code: req.body.project.code,
name: req.body.project.name
}
});
Returns an undefined error
Upvotes: 0
Views: 73
Reputation: 11975
You sent an object with project
field in the req.body
so you need to get it in this way:
const report = new Report({
project: {
studio: req.body.project.studio,
code: req.body.project.code,
name: req.body.project.name
}
});
If it still doen't work, maybe the Content-Type
of your request is not application/json
. Try adding it to the request header.
Note: Make sure you have body-parser in your app.
Upvotes: 1