我想通过将数组推入文档更新数据,但我在res.send(错误)中出错,这是我的代码:
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(错误)后的错误详细信息; :
{
"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'
}
});
感谢您的所有回复 .
4 回答
好吧,有多种原因导致您的代码无效 .
首先显示架构设计 . 可能存在缺陷 .
您通过 company.students.push(req.params.id) 实现此目的 .
如果要推送整个阵列,请尝试使用 company.students.push(students) .
记录错误对象 .
您正在尝试将字符串转换为objectId . 要保存该值,请使用mongoose.Types.ObjectId . 这将解决您的问题 . 如果有帮助,请告诉我 . 谢谢
Model.findById()
期望参数有效objectID
,并带有以下描述一个4字节的值,表示自Unix纪元以来的秒数,
一个3字节的机器标识符
一个2字节的进程ID,和
一个3字节计数器,以随机值开头 .
并且您的错误表明您正在尝试传递
"2"
,这不遵循objectId
标准 . 您应该将正确的ID传递给findById
.您可以使用
validator
来确定传递的id
参数是否正确 . 就像是你可以通过
npm install validator
安装它并通过验证身份
if(!validator.isMongoId(req.headers.postid)){ res.send("invalid post id ") }
PS .
validator
为您提供了非常漂亮的方法来验证不同的东西