bookmark.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. module.exports = function(app, models) {
  2. var mongoose = require('mongoose')
  3. , debug = require('debug')('crowi:models:bookmark')
  4. , ObjectId = mongoose.Schema.Types.ObjectId
  5. , bookmarkSchema;
  6. bookmarkSchema = new mongoose.Schema({
  7. page: { type: ObjectId, ref: 'Page', index: true },
  8. user: { type: ObjectId, ref: 'User', index: true },
  9. createdAt: { type: Date, default: Date.now() }
  10. });
  11. // bookmark チェック用
  12. bookmarkSchema.statics.findByPageIdAndUser = function(pageId, user, callback) {
  13. var Bookmark = this;
  14. Bookmark.findOne({ page: pageId, user: user._id }, callback);
  15. };
  16. bookmarkSchema.statics.findByUser = function(user, option, callback) {
  17. var Bookmark = this;
  18. var limit = option.limit || 50;
  19. var offset = option.skip || 0;
  20. Bookmark
  21. .find({ user: user._id })
  22. //.sort('createdAt', -1)
  23. .skip(offset)
  24. .limit(limit)
  25. .exec(function(err, bookmarks) {
  26. debug ('bookmarks', bookmarks);
  27. callback(err, bookmarks);
  28. });
  29. };
  30. bookmarkSchema.statics.add = function(page, user, callback) {
  31. var Bookmark = this;
  32. Bookmark.findOneAndUpdate(
  33. { page: page._id, user: user._id },
  34. { page: page._id, user: user._id, createdAt: Date.now() },
  35. { upsert: true, },
  36. function (err, bookmark) {
  37. debug('Bookmark.findOneAndUpdate', err, bookmark);
  38. callback(err, bookmark);
  39. });
  40. };
  41. bookmarkSchema.statics.remove = function(page, user, callback) {
  42. // To be implemented ...
  43. };
  44. models.Bookmark = mongoose.model('Bookmark', bookmarkSchema);
  45. return models.Bookmark;
  46. };