var UserSchema = new Schema({
job : [{
type : mongoose.Schema.Types.ObjectId,
experience : String,
grade : String,
ref: 'Company'}]
});
У пользователя может быть несколько заданий. Когда я добавить задание пользователю, мне нравится это:Ссылка на другую схему в Mongoose С дополнительными полями
Если у меня есть:
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
не определены. Как я могу указать эти поля?
EDIT:
Так я изменил 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));
});
}
Я получил (Внутренняя ошибка сервера) ошибка fr ом сервере
НО
//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
и experience
поле в MongoDB ...
Да, я думал, что-то вроде этого. Поэтому, я думаю, нет другого решения, верно? – Emidomh
@ Emidomh Я не думаю, что есть другое решение, извините:/ – GnsBeldaran
Я отредактировал мое сообщение, пожалуйста, взгляните :) – Emidomh