Friday, 28 April 2017

Mongoose : Add or Update model in node express

I have a model called Profile and has some user data in each profile. I am writing function when user tries to authenticated, it should check whether user exist or not using employee id (not objectId). If does not exist then add user but if it exist then update user(if any field is changed ex. phone number) or resolve (if data is not changed)

adding new user is working but i am not getting idea how to update. Here is function i am working on

public getProfile(userData: any) {
  //getting employee id from user data
  let emp_id = userData.mailNickname;
  return new Promise((resolve, reject) => {
  //finding user profile by employee id
  Profile.findOne({ emp_id: emp_id }, (err: Error, profile: any) => {
    if (err) throw err;
    //if employee exist then (here i need to put update)
    if (profile) {
      resolve(profile);
    } else { //(if user doesnot exist then adding)
      let newProfile = new Profile({
        emp-id: emp_id,
        firstName: userData.givenName,
        lastName: userData.surname,
        competency: '',
        jobTitle: userData.jobTitle,
        eMail: userData.mail,
        phone: userData.mobilePhone,
        pictureUrl: '',
        currentLocation: userData.city,
        baseLocation: '',
        vertical: userData.department,
        directReports: [],
        lastUpdate: new Date(),
        curatedSkills: [],
        uncuratedSkills: [],
        personalProfiles: [],
        mySkills: {
          primary: {
            level1: '',
            level2: '',
            level3: '',
            level4: '',
          },
          secondary: {
            level1: '',
            level2: '',
            level3: '',
            level4: '',
          },
          tertiary: {
            level1: '',
            level2: '',
            level3: '',
            level4: '',
          }
        }
      });
      newProfile.save((err: Error, profile: IProfile) => {
        if (err) throw err;
        resolve(profile);
      });
    }
  })
});
}



via ronypatil

No comments:

Post a Comment