I'd like to update data with push an array into the document, but I got an error in res.send(err), here is my code :
router.put('/update/:id', passport.authenticate('jwt', {session:false}), (req, res, next)=>{
User.findById(req.params.id, function(err, user) {
if(err) {
console.log(err);
return res.status(500).send({message: "Error"});
}
if(!user) {
return res.status(404).send({message: "User Not Found"});
}
Company.findById(req.body.company, function(err, company) {
var students = [req.params.id];
company.students = students.push(req.params.id);
// res.send(students);
company.save(function(err, company){
if(err){
return res.send(err);
// return res.status(500).send({message: "Cannot Update Company, please try again"});
}
return res.status(200).send({message: "Update User To Company Success.", company});
});
});
});
});
Here is the error details after return res.send(err); :
{
"errors": {
"students": {
"message": "Cast to ObjectID failed for value \"2\" at path \"students\"",
"name": "CastError",
"stringValue": "\"2\"",
"kind": "ObjectID",
"value": 2,
"path": "students",
"reason": {
"message": "Cast to ObjectId failed for value \"2\" at path \"students\"",
"name": "CastError",
"stringValue": "\"2\"",
"kind": "ObjectId",
"value": 2,
"path": "students"
}
}
},
"_message": "Company validation failed",
"message": "Company validation failed: students: Cast to ObjectID failed for value \"2\" at path \"students\"",
"name": "ValidationError"
}
Update, this is My Schema, I'd like to add id user from UserSchema to students in CompanySchema:
const CompanySchema = mongoose.Schema({
nama:{
type : String,
require : true
},
alamat:{
type : String,
require : true
},
email:{
type : String,
require : true
},
telepon:{
type : String,
require : true
},
website:{
type : String,
require : true
},
status:{
type : String,
require : true
},
students:{
type : mongoose.Schema.Types.ObjectId,
ref : 'users'
}
});
const CompanySchema = mongoose.Schema({
nama:{
type : String,
require : true
},
alamat:{
type : String,
require : true
},
email:{
type : String,
require : true
},
telepon:{
type : String,
require : true
},
website:{
type : String,
require : true
},
status:{
type : String,
require : true
},
students:{
type : mongoose.Schema.Types.ObjectId,
ref : 'users'
}
});
Thank you for all of your responses.
students
should be declared as an array likestudents: [{ type : mongoose.Schema.Types.ObjectId,ref : 'users' }]
– chridam