猫鼬参考被覆盖

时间:2016-12-24 13:15:02

标签: node.js mongodb express mongoose

我有点腌渍。每当我以登录用户创建新简历时,它都不会将简历ID添加为数组。即,[" 20293"," 2932392"," 32903239"]

相反,它会覆盖用户架构中的当前resume id。这是代码

UserSchema

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

2 个答案:

答案 0 :(得分:0)

这是错误的:

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做了两件事:

  1. 通过它的身份
  2. 查找文档
  3. 使用新数据更新
  4. 第二个参数是要设置的新数据。所以,第二步转化为:

    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: [
      {
         resume: {
           type: Schema.Types.ObjectId,
           ref: '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'
        },
        ...
      ]
    }
    

答案 1 :(得分:-1)

只是跟进我对我建议你如何解决问题的评论:

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

    //Here, instead of creating a new key entry for resume, you rather push new resume-id into the resume property of the "found user".      
      //find, update and save the user
      User.findOne({_id: req.user.sessionId}, function (err, userToUpdate) {
         userToUpdate.toJSON().resume.push(resume.id);
         userToUpdate.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
      });
    });

    }
  })
});

我将剩下的代码(保存新的简历)保持不变 - 我认为该部分有效。尝试一下,如果遇到一些问题,请告诉我。