Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mongoose = require('mongoose'),
- Schema = mongoose.Schema,
- ObjectId = Schema.ObjectId,
- UserSchema = require('./User').UserSchema;
- var FriendRequest = new Schema({
- from : {type: ObjectId, index:true}, // Why does not UserSchema.ObjectId work here, instead of ObjectId?
- to : {type: ObjectId, index:true},
- confirmed : {type: Boolean, index: true},
- created : {type: Date, default: Date.now},
- });
- FriendRequest.pre('save', function youCantBefriendYourself(next) {
- if (this.from == this.to) {
- next(new Error("A user can't befriend themselves."));
- } else {
- next();
- }
- });
- FriendRequest.pre('save', function lookForPendingRequest(next, done) {
- next();
- var query = {
- $or: [
- {'from': this.from,'to' : this.to},
- {'from': this.to,'to' : this.from}
- ]
- };
- mongoose.model('FriendRequest').find(query, function(err,res) {
- if (res.length > 0)
- done(new Error("Pending friendrequest exists already"));
- else
- done();
- });
- });
- // @untested
- FriendRequest.pre('save', function seeIfAlreadyFriends(next, done) {
- next();
- var query = {
- "_id" : this.from,
- "friends" : this.to
- };
- mongoose.model('User').find(query, function(err,res) {
- if (res.length > 0)
- done(new Error("The users are already friends"));
- else
- done();
- });
- });
- module.exports.FriendRequest = mongoose.model('FriendRequest', FriendRequest);
- module.exports.FriendRequestSchema = FriendRequest;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement