Reputation: 2573
i have a post function in my api file. i want to save an email in mongodb database using this post request:
rest-api/emails?from="[email protected]"&"to"="[email protected]"&subject="some subject"&content="some more content"&provider=sendgrid&success=false
i post method is like below :
.post((req, res)=>{
db.models.Email.create({from:req.body.from ,
to: req.body.to,
subject: req.body.subject,
content: req.body.content,
success: req.body.success,
provider: req.body.provider}, (err, result)=>{
if(err){
handleErrors(res, err);
console.log(`error in creating Email :${err}`)
}else {
console.log()
res.json(result)
}
});
});
after this post request only _id
, success
,provider
fields save in mongodb.
how can i fix this ?
EDIT: i remove all " from post request but still not saving correctly:
localhost:3000/rest-api/[email protected]&[email protected]&subject=somesubject&content=somemorecontent&provider=sendgrid&success=false
res:
{
"__v": 0,
"_id": "599add615fcb202b34c6a13e",
"success": false,
"provider": "sendgrid"
}
EDIT: model :
var ValidationError = mongoose.Error.ValidationError;
var Schema = mongoose.Schema;
mongoose.Promise = global.Promise ;
var validateEmail = function(email) {
if (email) return validator.isEmail(email);
return true;
}
var EmailSchema = new Schema({
from: {type: String, maxlength:100},
to: {type: String, maxlength:100},
subject: {type: String},
content: {type: String},
provider: {type: String, maxlength: 30, required: false, default: "sendgrid"},
sentdate: { type: Date },
success: {type: Boolean, default: false}
});
EmailSchema.pre('save',(next)=>{
// if(!this.sentdate){
// this.sentdate = Date.now();
// }
next();
});
EmailSchema.plugin(mongoosePaginate);
var Email = mongoose.model('Email',EmailSchema);
module.exports ={
models:{
Email
},
url: 'mongodb://localhost/emilapp',
}
req.body
console:
{}
req.body is empty!
Upvotes: 1
Views: 2520
Reputation: 9931
req.body
is meant to be used for post requests data whereas you are sending data as a GET request. Query strings sent to express server are stored in req.query
object. You need to modify our code to something like below.
.post((req, res)=>{
db.models.Email.create({from:req.query.from ,
to: req.query.to,
subject: req.query.subject,
content: req.query.content,
success: req.query.success,
provider: req.query.provider}, (err, result)=>{
if(err){
handleErrors(res, err);
console.log(`error in creating Email :${err}`)
}else {
console.log()
res.json(result)
}
});
});
Upvotes: 1
Reputation: 904
Make your you don't put " between strings. so the GET request should be like:
rest-api/[email protected]&[email protected]&subject=some
subject&content=some more content&provider=sendgrid&success=false
Upvotes: 0