Advertisement
Guest User

Untitled

a guest
Jan 25th, 2015
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. var mongoose = require('mongoose'),
  2. Schema = mongoose.Schema,
  3. ObjectId = Schema.ObjectId,
  4. UserSchema = require('./User').UserSchema;
  5.  
  6.  
  7. var FriendRequest = new Schema({
  8. from : {type: ObjectId, index:true}, // Why does not UserSchema.ObjectId work here, instead of ObjectId?
  9. to : {type: ObjectId, index:true},
  10.  
  11. confirmed : {type: Boolean, index: true},
  12.  
  13. created : {type: Date, default: Date.now},
  14. });
  15.  
  16. FriendRequest.pre('save', function youCantBefriendYourself(next) {
  17.  
  18. if (this.from == this.to) {
  19. next(new Error("A user can't befriend themselves."));
  20. } else {
  21. next();
  22. }
  23. });
  24.  
  25.  
  26. FriendRequest.pre('save', function lookForPendingRequest(next, done) {
  27. next();
  28. var query = {
  29. $or: [
  30. {'from': this.from,'to' : this.to},
  31. {'from': this.to,'to' : this.from}
  32. ]
  33. };
  34. mongoose.model('FriendRequest').find(query, function(err,res) {
  35. if (res.length > 0)
  36. done(new Error("Pending friendrequest exists already"));
  37. else
  38. done();
  39. });
  40. });
  41.  
  42. // @untested
  43. FriendRequest.pre('save', function seeIfAlreadyFriends(next, done) {
  44. next();
  45. var query = {
  46. "_id" : this.from,
  47. "friends" : this.to
  48. };
  49. mongoose.model('User').find(query, function(err,res) {
  50. if (res.length > 0)
  51. done(new Error("The users are already friends"));
  52. else
  53. done();
  54. });
  55. });
  56.  
  57. module.exports.FriendRequest = mongoose.model('FriendRequest', FriendRequest);
  58. module.exports.FriendRequestSchema = FriendRequest;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement