【问题标题】:Mongoose Subdocuments Throwing Required ValidationMongoose 子文档抛出所需的验证
【发布时间】:2015-09-30 22:28:52
【问题描述】:

这是我的架构

// 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 和受邀者 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
});

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

【问题讨论】:

    标签: node.js mongodb mongoose subdocument


    【解决方案1】:

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

    所以这是测试端的问题。

    【讨论】:

      猜你喜欢
      • 2018-10-31
      • 2019-06-03
      • 2014-09-15
      • 2014-08-27
      • 1970-01-01
      • 2018-04-15
      • 2020-05-22
      • 2012-09-11
      • 2019-12-09
      相关资源
      最近更新 更多