猫鼬子文档抛出所需的验证

Mongoose Subdocuments Throwing Required Validation

这是我的架构

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

通过 Postman,我将 createdby 和 invitees JSON 作为

[{"email": "1","phone": "1"},{"email": "2","phone": "2"}]

但是,我总是收到 phone 和电子邮件所需的错误。

我尝试了 Whosebug 的各种解决方案,但没有任何效果。我也尝试将单个值作为 {"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
});

谁能帮我指出我做错了什么?

好吧,经过多次尝试,我终于找到了解决办法。我的代码没有任何问题。问题出在 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 然后发送相同的字符串,效果很好。

原来是测试端的问题