我有点泡菜。每当我以登录用户身份创建新的简历时,都不会将简历ID添加为数组。即[[20293],“ 2932392”,“ 32903239”]

相反,它将覆盖用户架构中的当前简历ID。这是代码

用户架构

const UserSchema = new Schema({
    _vId: {
        type: String,
        default: id.generate()
    },
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    accountType: {
        type: String,
        enum: ['Alphaneer', 'Administrator', 'Support', 'PRO'],
        default: 'Alphaneer'
    },
    email: {
        type: String,
        required: true,
        trim: true
    },
    username: {
        type: String,
        required: true,
        trim: true,
        unique: true
    },
    bio: {
        type: String,
        default: "No bio provided."
    },
    // TODO: Hash the password before inserting as a document :)
    password: {
        type: String,
        required: true
    },
    createdAt: {
        type: String,
        default: moment(new Date()).format("MMM DD, YYYY") // "Sun, 3PM 17"
    },
    resume: [ { type: mongoose.Schema.ObjectId, ref: "Resume" } ]
});




我在哪里发布我的简历

 // POST /dashboard/resume/create
router.post('/resume/create', (req, res, next) => {
  Resume.create(req.body, (err, resume) => {
    if (err) {
      var err = new Error("Error:" + err);
      err.status = 404;
      next(err);
    } else {
      req.user = jwtDecode.decode(req.session.tokenID, 'secret');
      //I am assuming that you have saved your resume and getting the saved object in `resume`, now update the logged in user in req.user
      var user = req.user.sessionId;
      var updateData = {
        resume: resume._id
      }
      //save the updated user
      User.findByIdAndUpdate(user, updateData, function(err, user) {
        console.log(user);
        if (err) {
          res.json(err);
        } else {
          res.json(user);
        }
      })
    }
  })
});


gif of submitting new resumes

更新:

error picture

更新的代码:

// POST /dashboard/resume/create
router.post('/resume/create', (req, res, next) => {
  Resume.create(req.body, (err, resume) => {
    if (err) {
      var err = new Error("Error:" + err);
      err.status = 404;
      next(err);
    } else {
      req.user = jwtDecode.decode(req.session.tokenID, 'secret');
      //I am assuming that you have saved your resume and getting the saved object in `resume`, now update the logged in user in req.user
      var user = req.user.sessionId;
      var updateData = {
        resume: resume._id
      }
      //save the updated user
      User.findById(user, function(err, user) {
        console.log(user);
        if (err) {
          res.json(err);
        } else {
          user.resume.push(resume.id)
          user.save(function(user) {
            return res.json(user);
          });
        }
      })
    }
  })
});

最佳答案

这是错误的:

var user = req.user.sessionId;
  var updateData = {
    resume: resume._id
  }
  //save the updated user
  User.findByIdAndUpdate(user, updateData, function(err, user) {
    console.log(user);
    if (err) {
      res.json(err);
    } else {
      res.json(user);
    }
  });


resume字段是一个数组,您将其作为字符串字段进行操作。方法findOneAndUpdate做两件事:


通过ID查找文档
用新数据更新


第二个参数是要设置的新数据。因此,第二步翻译为:

User.upate({ _id: user }, { resume: resume._id });


你看到什么问题了吗? resume必须存储一个简历ID数组,您正在将ID设置为值。显然,这将引发MongooseError。

您的第二张照片是正确的,但有错字:

User.findById(user, function(err, user) {
    console.log(user);
    if (err) {
      res.json(err);
    } else {
      user.resume.push(resume.id)
      user.save(function(user) {
        return res.json(user);
      });
    }
  });


您必须添加_id字段,因为这是新创建的文档(恢复)的ObjectID。因此,您需要改为执行user.resume.push(resume._id)

更新资料

根据您的最新评论,您想填充用户模型,即通过关联ID检索所有模型数据。在这种情况下,建议对resumes数组进行如下更改:

...
resumes: [
  {
     resume: {
       type: Schema.Types.ObjectId,
       ref: 'Resume'
     }
   }
 ]


要用所有Resume数据填充用户文档,您只需要引用resume字段数组中的resumes键。

User.findById(user, function(err, user) {
    if (err) {
      return res.json({ success: false, message: err.message });
    }
    user.resume.push(resume.id)
    user.save(function(err, user) {
      if (err) {
        return res.json({ success: false, message: err.message });
      }
      // save was fine, finally return the user document populated
      User.findById(user).populate('resumes.resume').exec(function(err, u) {
        return res.json(u);
      });
    });
  }
});


populate方法接受一个字符串,其中包含我们要用其填充模型数据的字段。您的情况是唯一字段(resume)。运行查询后,您将获得以下内容:

{
  _id: a939v0240mf0205jf48ut84sdfdjg4,
  ...,
  resumes: [
    resume: {
      _id: f940tndfq4ut84jofgh03ut85dg9454g,
      title: 'Some title'
    },
    ...
  ]
}

10-07 14:04