AllenYuan

following feature

May 16th, 2020
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
  2.  
  3. // ...
  4.  
  5. // add user to the followed list
  6. UserSchema.methods.follow = function(id){
  7.   if (this.following.indexOf(id) === -1){
  8.     this.following = this.following.concat([id]);
  9.   }
  10.   return this.save();
  11. }
  12.  
  13. // remove the user from the followed list
  14. UserSchema.methods.unfollow = function(id){
  15.   this.following.remove(id);
  16.   return this.save();
  17. }
  18.  
  19. // see if we're following this user
  20. UserSchema.methods.isFollowing = function(id){
  21.   return this.following.some(function(followId){
  22.     return followId.toString() === id.toString();
  23.   })
  24. }
  25.  
  26. UserSchema.methods.toProfileJSONFor = function (user) {
  27.   return {
  28.     username: this.username,
  29.     bio: this.bio,
  30.     image:
  31.       this.image || 'https://static.productionready.io/images/smiley-cyrus.jpg',
  32.     // true if we're following the given user, false otherwise
  33.     following: user ? user.isFollowing(this._id) : false,
  34.   };
  35. };
  36.  
  37. // register the schema with mongoose as 'User'
  38. mongoose.model('User', UserSchema);
Add Comment
Please, Sign In to add comment