<commit_before>var db = require('mongoose')
  , uuid = require('node-uuid');

var ObjectId = db.Schema.ObjectId;
var Schema = new(db.Schema)({
  name: {type: String, trim: true, required: true},
  description: {type: String, trim: true, required: true},
  user: {type: ObjectId, ref: 'User', required: true},
  key: db.Schema.Types.Mixed,
});

var Device = db.model('Device', Schema);
Schema.pre('save', function(next) {
  var genCredentials, key, token, that = this;

  if (!this.isNew) {
    return next();
  }
  
  (genCredentials = function() {
    key = uuid.v1();
    token = genToken();
    
    Device.find(
      {'key.key': key, 'key.token': token}, function(err, devices) {
	if (err) {
	  next(err);
	  return;
	}

	if (devices.length > 0) {
	  genCredentials();
	  return;
	}

	that.key = {key: key, token: token};
	next();
      }
    );
  })();
});

Schema.post('save', function() {
  var User = db.model('User'), that = this;
  
  User.update(
    {_id: this.user}, {$addToSet: {devices: this.key.key}}, function(err) {
      if (err) {
	next(err);
      }
    }
  );
});<commit_msg>Ensuring that every device key has to be unique<commit_after>var db = require('mongoose')
  , uuid = require('node-uuid');

var ObjectId = db.Schema.ObjectId;
var Schema = new(db.Schema)({
  name: {type: String, trim: true, required: true},
  description: {type: String, trim: true, required: true},
  user: {type: ObjectId, ref: 'User', required: true},
  key: db.Schema.Types.Mixed,
});

var Device = db.model('Device', Schema);
Schema.pre('save', function(next) {
  var genCredentials, key, token, that = this;

  if (!this.isNew) {
    return next();
  }
  
  (genCredentials = function() {
    key = uuid.v1();
    token = genToken();
    
    Device.find(
      {'key.key': key}, function(err, devices) {
	if (err) {
	  next(err);
	  return;
	}

	if (devices.length > 0) {
	  genCredentials();
	  return;
	}

	that.key = {key: key, token: token};
	next();
      }
    );
  })();
});

Schema.post('save', function() {
  var User = db.model('User'), that = this;
  
  User.update(
    {_id: this.user}, {$addToSet: {devices: this.key.key}}, function(err) {
      if (err) {
	next(err);
      }
    }
  );
});
{'fraction_non_alphanumeric': 0.19230769230769232, 'fraction_numerical': 0.0018099547511312218, 'mean_word_length': 3.125, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4853181', 'n_tokens_mistral': 810, 'n_tokens_neox': 805, 'n_words': 196}