这是我的架构
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = require('./user');
var inviteeSchema = new Schema({
email: { type: String, required: true, unique: true },
phone: { type: String, required: true, unique: true },
});
// create a schema
var sessionSchema = new Schema({
createdby: { type: String, required: true, unique: true },
invitees: [inviteeSchema],
created_at: Date,
updated_at: Date
});
// on every save, add the date
sessionSchema.pre('save', function(next) {
// get the current date
var currentDate = new Date();
// change the updated_at field to current date
this.updated_at = currentDate;
// if created_at doesn't exist, add to that field
if (!this.created_at)
this.created_at = currentDate;
next();
});
// the schema is useless so far
// we need to create a model using it
var Session = mongoose.model('Session', sessionSchema);
// make this available to our users in our Node applications
module.exports = Session;
现在,我正在进行保存
router.post('/', function(req, res) {
var session = new Session();
//res.send(req.body);
session.createdby = req.body.createdby;
session.invitees.push({invitees: req.body.invitees});
session.save(function(err) {
if(err) res.send(err);
res.json({status: 'Success'});
});
});
通过邮递员,我传递了createdby和被邀请者JSON为
[{"email": "1","phone": "1"},{"email": "2","phone": "2"}]
但是,我总是收到手机和电子邮件所需的错误。
我尝试了stackoverflow的各种解决方案,但没有任何效果。我也尝试将单个值传递为{"email": "1","phone": "1"}
,但它也会抛出错误。
我甚至尝试修改我的架构如下,但我仍然得到验证错误。
var sessionSchema = new Schema({
createdby: { type: String, required: true, unique: true },
invitees: [{
email: { type: String, required: true, unique: true },
phone: { type: String, required: true, unique: true }
}],
created_at: Date,
updated_at: Date
});
任何人都可以帮我指出我做错了什么吗?
答案 0 :(得分:0)
好吧,经过多次尝试后,我找到了解决方案。我的代码没有错。问题出在Postman。
router.post('/', function(req, res) {
var session = new Session(req.body);
session.save(function(err) {
if(err) res.send(err);
res.json({status: 'Success'});
});
});
当我通过Postman传递[{"email": "1","phone": "1"},{"email": "2","phone": "2"}]
时,它被转换为字符串,因为我选择了xxx-form-urlencoded。我需要选择raw和application / json,然后发送相同的字符串,工作正常。
所以测试结束时出现问题。