AllenYuan

articleSchema favoritecount

May 11th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var mongoose = require('mongoose');
  2. var uniqueValidator = require('mongoose-unique-validator');
  3. var slug = require('slug'); // package for auto-creating URL slugs
  4. var User = mongoose.model('User');
  5.  
  6. //...
  7.  
  8. // this is really slow for a large collection of users, but it gives an accurate result.
  9. // iterate over all users and count how many have this article in their favorite list
  10. ArticleSchema.methods.updateFavoriteCount = function() {
  11.   var article = this;
  12.   return User.count({favorites: {$in: [article._id]}}).then(function(count){
  13.     article.favoritesCount = count;
  14.     return article.save();
  15.   });
  16. };
  17.  
  18. mongoose.model('Article', ArticleSchema);
Advertisement
Add Comment
Please, Sign In to add comment