Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored the code to allow the use of the mongoose plugins #16

Closed
wants to merge 2 commits into from

Conversation

haohello
Copy link

Refactored the code to allow the use of the mongoose plugins, also update the package dependencies, test and example code to the latest.

Well, I have such a usage scenario to use mongoose plugins and also add custom model methods in my models as such:

// Get Mongoose
var mongoose = require('mongoose');

// Connect to your MongoDB
mongoose.connect('mongodb://localhost/user-todos');

var mongooseService = require('feathers-mongoose');

var Schema = mongoose.Schema;

var timestamps = require('mongoose-timestamp');

var Token = new Schema({
  token: {type: String},
  date_created: {type: Date, default: Date.now}
});

Token.statics.hasExpired= function(created) {
  var now = new Date();
  var diff = (now.getTime() - created);
  return diff > config.token.ttl;
};
var TokenModel = mongoose.model('Token', Token);

var UserSchema = new Schema({
  email: {type : String, required : true, index: {unique: true, dropDups: true}},
  firstName: {type : String, required : true},
  lastName: {type : String, required : true},
  age: {type : Number, required : true},
  tokens: {
    type: [Token]
  },
  password: {type : String, required : true, select: false},
  skills: {type : Array, required : true}
});

UserSchema.plugin(timestamps);

UserSchema.statics.findUser = function(email, token, cb) {
  var self = this;
  this.findOne({email: email}, function(err, usr) {
    if(err || !usr) {
      cb(err, null);
    } else if (usr.token && usr.token.token && token === usr.token.token && !TokenModel.hasExpired(usr.token.date_created)) {
      cb(false, {email: usr.email, token: usr.token, createdAt: usr.createdAt, name: usr.name});
    } else {
      cb(new Error('Token does not exist or does not match.'), null);
    }
  });
};

UserSchema.statics.findUserByEmailOnly = function(email, cb) {
  var self = this;
  this.findOne({email: email}, function(err, usr) {
    if(err || !usr) {
      cb(err, null);
    } else {
      cb(false, usr);
    }
  });
};

var UserModel = mongoose.model('User', UserSchema);

@ekryski
Copy link
Member

ekryski commented Aug 5, 2015

Closed by PR #18.

@ekryski ekryski closed this Aug 5, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants