引用猫鼬中带有额外字段的另一个模式

Referencing another schema in Mongoose WITH extra fields

本文关键字:字段 另一个 模式 引用      更新时间:2023-09-26
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" 由猫鼬保留,然后

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

描述具有 ObjectId 类型的实体,引用公司(此实体与 .populate 一起使用)。不幸的是,由于它作为ObjectId保存在MongoDB中,因此其他字段将被忽略。

然后,您可以选择在其中一个字段中引用公司,并能够使用 JobSchema 检索额外的信息位,例如:

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

您将能够填充工作_company领域,而不会丢失"经验"和"等级"信息


在您的版本之后:

使用给定的作业模式:

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

您的作业实例应类似于 {_company: ObjectId("......."), 体验: "blabla", grade: "smth"}。那么你的req.body.job应该是{_company: company._id, 经验: "bla bla", grade : "smth"}

在你的第一个addJob中,你有一个500错误,因为你要求MongoDB将一个看起来像{type: ObjectId("....")}的文档转换为ObjectId。

第二个 addJob 不会触发错误,因为您正在上传一个看起来像 {type: ObjectId("...")} 的文档(顺便说一下,丢失了成绩和经验字段),并且您的架构字段都不是必需的,因此猫鼬忽略您的字段类型并将空对象上传到您的集合中。

博士:它应该是:

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