1

I have a mongoose schema like

var userSchema = new mongoose.Schema({
  friends: [String]
});
var User = mongoose.model('User', userSchema);
var alice = new User({friends: ['bob']});

and I would like to attach an instance method to the friends array, e.g., a function myFunction that can be called like

alice.friends.myFunction(...);

Does mongoose provide a way to do so?

PS: here, @wciu asked if a function can be defined on the subdocuments itself (which is possible). The question here is if it is possible to define it on the array.

Community
  • 1
  • 1
andrenarchy
  • 448
  • 3
  • 12
  • 1
    In this case `alice.friends` is already an array object, so it wouldn't make sense to add custom functions to it, unless you'd like to add a prototype to the Array object. What kind of logic would you like to apply within your function? My answer would vary based on what you're trying to accomplish. – Brian Shamblen Jan 07 '15 at 22:23
  • I'd like to add authorization wrappers for creating, modifying and deleting array elements that take into account the permissions of the user that initiated the operation. – andrenarchy Jan 08 '15 at 11:32
  • @andrenarchy That's probably best handled outside of your Mongoose ORM layer. – JohnnyHK Jan 08 '15 at 14:39

0 Answers0