0

这是我的架构

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

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

4

1 回答 1

0

好吧,终于在尝试了很多之后,我找到了解决方案。我的代码没有任何问题。问题出在邮递员身上。

router.post('/', function(req, res) {
  var session = new Session(req.body);

  session.save(function(err) {
    if(err) res.send(err);
    res.json({status: 'Success'});
  });
});

当我[{"email": "1","phone": "1"},{"email": "2","phone": "2"}]通过 Postman 时,它被转换为字符串,因为我选择了 xxx-form-urlencoded。我需要选择 raw 和 application/json 然后发送相同的字符串,它工作正常。

所以这是测试端的问题。

于 2015-07-14T17:10:14.903 回答