简体   繁体   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'}]
});

User can have several jobs. 用户可以有多个作业。 When I add a job to the user, I do like this : 当我向用户添加作业时,我会这样:

If I have : 如果我有 :

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

and

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

I got an error : 我有一个错误:

Unhandled rejection CastError: Cast to ObjectId failed for value "[object Object]" at path "job"

But if i do : 但是,如果我这样做:

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

with

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

It works but experience and grade are undefined. 它可以工作,但是experiencegrade是不确定的。 How can I specify those fields ? 如何指定这些字段?


EDIT : 编辑:

So I changed UserSchema like : 所以我像这样更改了UserSchema

var UserSchema = new Schema({
  job : [{
    _company : {
      type : mongoose.Schema.Types.ObjectId,
      ref: 'Company'
    },
    experience : String,
    grade : String
    }]
});

And I tried : 我试过了:

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

I got an 500 (Internal Server Error) error from server 我从服务器收到500(内部服务器错误)错误

BUT

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

Works without error. 可以正常工作。 However there is still nothing about grade and experience field in mongodb... 但是,在mongodb中,关于gradeexperience领域仍然一无所有...

The field "type" is reserved by Mongoose, then 猫鼬保留了“类型”字段,然后

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

is describing an entity with a type of ObjectId, referencing a Company (this one is used with .populate). 正在描述一种类型为ObjectId的实体,该实体引用公司(此实体与.populate一起使用)。 Unfortunately, since it is saved in MongoDB as an ObjectId, the other fields will be ignored. 不幸的是,由于它作为对象ID保存在MongoDB中,因此其他字段将被忽略。

You can then choose to reference the company in one of the fields, and be able to retrieve the extra bits of information with a JobSchema like : 然后,您可以选择在其中一个字段中引用公司,并可以使用JobSchema检索额外的信息:

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

You will be able to populate the _company field of your jobs without losing the "experience" and "grade" information 您将能够填充工作的_company字段,而不会丢失“经验”和“等级”信息


After your edition : 在您的版本之后:

With the given JobSchema : 使用给定的JobSchema:

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

Your job instance should look like {_company: ObjectId("......."), experience : "blabla", grade: "smth"}. 您的工作实例应类似于{_company:ObjectId(“ .......”),经验:“ blabla”,等级:“ smth”}。 Then your req.body.job should be {_company: company._id, experience : "bla bla", grade : "smth"} 然后,您的req.body.job应该是{_company:company._id,经验:“ bla bla”,等级:“ smth”}

In your first addJob, you have a 500 error because you are asking MongoDB to cast a document that looks like {type: ObjectId("....")} into an ObjectId. 在您的第一个addJob中,您遇到500错误,因为您要求MongoDB将看起来像{type:ObjectId(“ ....”)}的文档转换为ObjectId。

The second addJob doesn't trigger an error because you are uploading a document that looks like {type: ObjectId("...")} (and losing the grade and experience fields by the way) and none of your Schema fields are required so mongoose is ignoring your field type and uploads an empty object into your collection. 第二个addJob不会触发错误,因为您正在上载一个看起来像{type:ObjectId(“ ...”)}的文档(并且会丢失成绩和经验字段),并且不需要任何Schema字段因此猫鼬会忽略您的字段类型,并将一个空对象上传到您的集合中。

tl;dr: It should be : 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