AllenYuan

userschema favoriting

May 11th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //...
  2.     favorites: [{type: mongoose.Schema.Types.ObjectId, ref: 'Article' }],
  3.   },
  4.   {timestamps: true}
  5. );
  6.  
  7. UserSchema.plugin(uniqueValidator, {message: 'is already taken.'});
  8.  
  9. // push article id to favorites list and save the state of the user
  10. UserSchema.methods.favorite = function (id) {
  11.   if (this.favorites.indexOf(id) === -1) {
  12.     this.favorites = this.favorites.concat([id]);
  13.     console.log('favorites after favoriting', this.favorites);
  14.     console.log('article id', id);
  15.   }
  16.   return this.save();
  17. };
  18.  
  19. // remove article from favorites list and save state
  20. UserSchema.methods.unfavorite = function(id){
  21.   this.favorites.remove(id);
  22.   return this.save();
  23. }
  24.  
  25. //...
Advertisement
Add Comment
Please, Sign In to add comment