用post api将数据保存到mongodb

我有我的API文件中的职位function。 我想要保存一个电子邮件在MongoDB数据库使用这个post请求:

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) } }); }); 

经过这个职位请求只有_idsuccessprovider领域保存在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 console:{} req.body is empty!

req.body是用来发送请求数据,而你是发送数据作为GET请求。 发送到express服务器的查询string存储在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) } }); }); 

让你不要放在string之间,所以GET请求应该是这样的:

 rest-api/emails?from=test@mail.com&to=test@test.com&subject=some subject&content=some more content&provider=sendgrid&success=false