Created
November 30, 2012 03:59
-
-
Save jwietelmann/4173699 to your computer and use it in GitHub Desktop.
Mongoose plugin for keeping unique ObjectId ref Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey there!
This code is very unsafe:
this[field]
, your code will delete the last element in thethis[field]
this[field]
this code will DELETE WHOLE array. Check http://www.w3schools.com/jsref/jsref_splice.asp