node 添加个人经历的接口

1.定义experience 

 const  profileFields = {};
      profileFields.experience=[];

  

2.查找用户id

 const profile = await Profile.find({ user: ctx.state.user.id });

3.判断用户的数据是否存在,

如果存在,就设计数据的结构,然后添进Profile 中,最后更新进去数据库里面

if(profile.length>0) {
        //设计experience 的结构数据
         const  newExp={
          title: ctx.request.body.title,
          current: ctx.request.body.current,
          company: ctx.request.body.company,
          location: ctx.request.body.location,
          from: ctx.request.body.from,
          to: ctx.request.body.to,
          description: ctx.request.body.description
         }
         profileFields.experience.unshift(newExp);
         //console.log(profileFields);
         //在从前端添加数据后,我们更新数据到数据库
         const  profileUpdate =  await   Profile.findOneAndUpdate(
          {
           user:ctx.state.user.id
          },
          {
            $set:profileFields
          },
          {
             new:true
          }
      );
          ctx.body=profileUpdate;

更新数据库

  const  profileUpdate =  await   Profile.findOneAndUpdate(
          {
           user:ctx.state.user.id
          },
          {
            $set:profileFields
          },
          {
             new:true
          }

  数据不存在

 errors.noprofile = '没有该用户的信息';
        ctx.status = 404;
        ctx.body = errors

代码

/**
 * @route post api/profile/experience
 * @desc  工作经历接口
 * @access 接口是私密的
 */
// localhost:4000/api/profile/experience
router.post('/experience', passport.authenticate('jwt', { session: false }), async ctx => {
    //验证
    const { errors, isValid } = validateExperienceInput(ctx.request.body);
    //判断是否验证通过
    if (!isValid) {
      ctx.status = 400;
      ctx.body = errors;
      return;
    }
      const  profileFields = {};
      profileFields.experience=[];
      //查找用户id是否存在
      const profile = await Profile.find({ user: ctx.state.user.id });
      //判断profile  的数据是否存在,存在就添加个人经历的数据
      if(profile.length>0) {
        //设计experience 的结构数据
         const  newExp={
          title: ctx.request.body.title,
          current: ctx.request.body.current,
          company: ctx.request.body.company,
          location: ctx.request.body.location,
          from: ctx.request.body.from,
          to: ctx.request.body.to,
          description: ctx.request.body.description
         }
         profileFields.experience.unshift(newExp);
         //console.log(profileFields);
         //在从前端添加数据后,我们更新数据到数据库
         const  profileUpdate =  await   Profile.findOneAndUpdate(
          {
           user:ctx.state.user.id
          },
          {
            $set:profileFields
          },
          {
             new:true
          }
      );
          ctx.body=profileUpdate;
    
      }else {
        errors.noprofile = '没有该用户的信息';
        ctx.status = 404;
        ctx.body = errors;
      }
      
  
});

  截图

猜你喜欢

转载自www.cnblogs.com/guangzhou11/p/10340188.html