Skip to content

Instantly share code, notes, and snippets.

@jwietelmann
Created November 30, 2012 03:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jwietelmann/4173699 to your computer and use it in GitHub Desktop.
Save jwietelmann/4173699 to your computer and use it in GitHub Desktop.
Mongoose plugin for keeping unique ObjectId ref Arrays
module.exports = function(schema, options) {
schema.method('addUniqueRef', function(field, item) {
if(this[field].indexOf(item) < 0) this[field].push(item);
});
schema.method('removeUniqueRef', function(field, item) {
this[field].splice(this[field].indexOf(item));
});
};
@kkozionov
Copy link

Hey there!
This code is very unsafe:

  • If you remove the item which was not found in this[field], your code will delete the last element in the this[field]
  • If you remove the first element in the this[field] this code will DELETE WHOLE array. Check http://www.w3schools.com/jsref/jsref_splice.asp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment