var UserSchema = new Schema({
job : [{
type : mongoose.Schema.Types.ObjectId,
experience : String,
grade : String,
ref: 'Company'}]
});
用戶可以有多個作業。當我添加作業到用戶,我這樣做:引用在貓鼬的另一個架構使用額外字段
如果我有:
req.body.job == {type : company._id, experience : "bla bla", grade : "smth"}
和
function addJob(req, res, next) {
var userId = req.user._id;
var job = req.body.job;
return User.findById(userId).exec()
.then(user => {
user.job.push(job);
return user.save()
.then(handleEntityNotFound(res))
.then(respondWithResult(res))
.catch(handleError(res));
});
}
我得到了一個錯誤:
Unhandled rejection CastError: Cast to ObjectId failed for value "[object Object]" at path "job"
但如果我這樣做:
req.body.job == {type : company._id, experience : "bla bla", grade : "smth"}
與
function addJob(req, res, next) {
var userId = req.user._id;
var job = req.body.job;
return User.findById(userId).exec()
.then(user => {
user.job.push(job.type); // <----------
return user.save()
.then(handleEntityNotFound(res))
.then(respondWithResult(res))
.catch(handleError(res));
});
}
它的工作原理,但experience
和grade
是不確定的。我如何指定這些字段?
編輯:
因此,我改變UserSchema
這樣的:
var UserSchema = new Schema({
job : [{
_company : {
type : mongoose.Schema.Types.ObjectId,
ref: 'Company'
},
experience : String,
grade : String
}]
});
而且我想:
//req.body.job == {_company:{type : company._id}, experience : "bla bla", grade : "smth"}
function addJob(req, res, next) {
var userId = req.user._id;
var job = req.body.job;
return User.findById(userId).exec()
.then(user => {
user.job.push(job);
return user.save()
.then(handleEntityNotFound(res))
.then(respondWithResult(res))
.catch(handleError(res));
});
}
我得到了一個500(內部服務器錯誤)錯誤fr OM服務器
但
//req.body.job == {_company:{type : company._id}, experience : "bla bla", grade : "smth"}
function addJob(req, res, next) {
var userId = req.user._id;
var job = req.body.job;
return User.findById(userId).exec()
.then(user => {
user.job.push(job._company); //<-----------------
return user.save()
.then(handleEntityNotFound(res))
.then(respondWithResult(res))
.catch(handleError(res));
});
}
而不會出現錯誤。但是仍然有任何關於grade
和MongoDB中experience
場...
是的,我想是這樣的。所以我想沒有其他的解決方案,對吧? – Emidomh
@Emidomh我不認爲有另一種解決方案,對不起:/ – GnsBeldaran
我編輯我的文章,請看看:) – Emidomh