1

I'm new to mongodb, node and express. I I'm trying to save these data in mongodb.

I have staff.model.js as follows

let StaffSchema = new Schema({
    staffcode:String,
    firstname:String,
    lastname: String,
    type: String,
    department:String,
    dateofjoin:Date,
    lastworkingday:Date,
    teaching:[ {type:Schema.Types.ObjectId, ref:'Teaches'} ]
});

I have another schema named teaches as follows

let TeachesSchema = new Schema({
    standard:{type: Schema.Types.ObjectId, ref: 'Standard'},
    subjects:[{type: Schema.Types.ObjectId, ref: 'Subject'}]
});

another schema of standards as follows

let StandardSchema = new Schema({
    name:String,
    medium:String,
    section:String
});

another schema subjects as follows

let SubjectSchema = new Schema({
    name:{ type: String, required: true, max: 25 }
});

finally I'm trying to save data in mogodb as like

exports.staff_create = function(req, res){
    let staff = new Staff({
        staffcode:req.body.staffcode,
        firstname:req.body.firstname,
        lastname: req.body.lastname,
        type: req.body.type,
        department:req.body.department,
        dateofjoin:req.body.dateofjoin,
        teaching:req.body.teaching
    });
    staff.save(function(err){
        if(err){
            return next(err);
        }
        res.send('Staff created successfully');
    });
};

making api call from postman with input like this

{
  "staffcode": "STF0003",
  "firstname": "Joh Doe",
  "lastname": "Moy",
  "type": "teaching",
  "department": "physics",
  "dateofjoin": "2018-06-01",
  "teaching": {
    "standard": {
      "_id": "5cb8ff551a1c1a2514fa467c",
      "name": "1",
      "medium": "English",
      "section": "A"
    },
    "subjects": [
      {
        "_id": "5cb8ed65c068b22f5489d050"
      },
      {
        "_id": "5cb8ed6bc068b22f5489d051"
      }
    ]
  }
}

what is wrong in this? I'm not able to get success response in postman request.

James Z
  • 12,209
  • 10
  • 24
  • 44
Naveen Bathina
  • 404
  • 1
  • 6
  • 25

1 Answers1

0

your schema design is coming from relational databases. However you can do what you ask by using populate.

a better way would be to use embedded documents instead of referrals in some places check this answer about MongoDB relationships: embed or reference?

Hassan Juniedi
  • 403
  • 5
  • 14