簡體   English   中英

用額外的字段引用Mongoose中的另一個模式

[英]Referencing another schema in Mongoose WITH extra fields

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));
        });
    }

它可以工作,但是experiencegrade是不確定的。 如何指定這些字段?


編輯:

所以我像這樣更改了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(內部服務器錯誤)錯誤

//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));
    });
}

可以正常工作。 但是,在mongodb中,關於gradeexperience領域仍然一無所有...

貓鼬保留了“類型”字段,然后

{
    type : mongoose.Schema.Types.ObjectId,
    experience : String,
    grade : String,
    ref: 'Company'
}

正在描述一種類型為ObjectId的實體,該實體引用公司(此實體與.populate一起使用)。 不幸的是,由於它作為對象ID保存在MongoDB中,因此其他字段將被忽略。

然后,您可以選擇在其中一個字段中引用公司,並可以使用JobSchema檢索額外的信息:

{
    _company : {type: mongoose.Schema.Types.ObjectId, ref: 'Company'}
    experience : String,
    grade : String
}

您將能夠填充工作的_company字段,而不會丟失“經驗”和“等級”信息


在您的版本之后:

使用給定的JobSchema:

{
    _company : {type: mongoose.Schema.Types.ObjectId, ref: 'Company'}
    experience : String,
    grade : String
}

您的工作實例應類似於{_company:ObjectId(“ .......”),經驗:“ blabla”,等級:“ smth”}。 然后,您的req.body.job應該是{_company:company._id,經驗:“ bla bla”,等級:“ smth”}

在您的第一個addJob中,您遇到500錯誤,因為您要求MongoDB將看起來像{type:ObjectId(“ ....”)}的文檔轉換為ObjectId。

第二個addJob不會觸發錯誤,因為您正在上載一個看起來像{type:ObjectId(“ ...”)}的文檔(並且會丟失成績和經驗字段),並且不需要任何Schema字段因此貓鼬會忽略您的字段類型,並將一個空對象上傳到您的集合中。

tl; dr:應該是:

// req.body.job == {_company: company._id, experience : "bla bla", grade : "smth"}

function addJob(req, res, next) {
    var userId = req.user._id, 
        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));
                   }
               );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM