【发布时间】:2018-09-14 19:50:23
【问题描述】:
我想通过将数组推送到文档来更新数据,但我在 res.send(err) 中遇到错误,这是我的代码:
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});
});
});
});
});
这里是返回 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"
}
更新,这是我的架构,我想将 UserSchema 中的 id 用户添加到 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'
}
});
感谢您的所有回复。
【问题讨论】:
-
您的代码返回错误“无法更新公司,请重试”。而不是这样做,你为什么不也包括来自对象“err”的信息,而不是丢弃它。它会给你更多关于正在发生的事情的线索。
-
我建议您打印 company 对象并打印 err 对象。这将使您对出了什么问题有更多的了解。可能数据并没有完全按照您的模型需要。
-
在您的架构中,
students应声明为类似students: [{ type : mongoose.Schema.Types.ObjectId,ref : 'users' }]的数组
标签: node.js mongodb mongoose mean-stack