我的api文件中有一个post函数。我想使用此帖子请求在mongodb数据库中保存电子邮件:
rest-api/emails?from="test@mail.com"&"to"="test@test.com"&subject="some subject"&content="some more content"&provider=sendgrid&success=false
我发布的方法如下:
.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)
}
});
});
此帖子请求后,只有_id
,success
,provider
字段保存在mongodb中。
我该如何解决这个问题?
编辑: 我从发布请求中删除所有“但仍未正确保存:
localhost:3000/rest-api/emails?from=example@example.com&to=test@test.com&subject=somesubject&content=somemorecontent&provider=sendgrid&success=false
RES:
{
"__v": 0,
"_id": "599add615fcb202b34c6a13e",
"success": false,
"provider": "sendgrid"
}
编辑: 型号:
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
控制台:
{}
req.body是空的!
答案 0 :(得分:1)
req.body
用于发布请求数据,而您将数据作为GET请求发送。发送到express服务器的查询字符串存储在req.query
对象中。您需要将我们的代码修改为以下内容。
.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)
}
});
});
答案 1 :(得分:0)
让你不要把“放在字符串之间。所以GET请求应该是:
rest-api/emails?from=test@mail.com&to=test@test.com&subject=some
subject&content=some more content&provider=sendgrid&success=false