作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我想通过将数组推送到文档来更新数据,但是我在 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});
});
});
});
});
这里是 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"
}
更新,这是我的架构,我想将 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'
}
});
感谢您的所有回复。
最佳答案
您正在尝试将字符串转换为 objectId。要保存该值,请使用 mongoose.Types.ObjectId。那会解决你的问题。让我知道是否有帮助。谢谢
关于node.js - 如何在 Mongoose 中推送数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49664748/
我是一名优秀的程序员,十分优秀!