This is my schema
// 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;
And now, I'm doing the save as
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'});
});
});
Via Postman, I'm passing the createdby and invitees JSON as
[{"email": "1","phone": "1"},{"email": "2","phone": "2"}]
But, I'm always getting required error for phone and email.
I tried various solutions from stackoverflow, but nothing worked. I also tried passing single value as {"email": "1","phone": "1"}
but it throws error too.
I even tried modifying my schema as below, but I still get validation error.
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
});
Can anyone help me pointing out what am I doing wrong?
Well, finally after trying a lot, I found the solution. There was nothing wrong in my code. The problem was in 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'});
});
});
When I was passing [{"email": "1","phone": "1"},{"email": "2","phone": "2"}]
via Postman, it was getting converted into string as I had choose xxx-form-urlencoded. I needed to choose raw and application/json and then send the same string which worked fine.
So it was problem in the testing end.