6

If I have a a Schema in Mongoose that's defined like:

var subSchema = new Schema({
  some: String
});

var topSchema = new Schema({
  subs: [subSchema]
});

var topModel = mongoose.model("Top", topSchema);

Is it possible to define an instance method for the sub document? I've tried the following(added before the model declaration), but it doesn't work:

subSchema.methods.someFn = function() { 
  return 'blah';
};
wciu
  • 1,183
  • 2
  • 9
  • 24

1 Answers1

3

Answering my own question.

What I originally wanted to do was to create a function that can be used on the collection of subdocs, as in:

topdoc.subs.someFn();

However, what I actually did with code in the original question was create a function for a subdoc itself, as in:

topdoc.subs[i].someFn();

This works.

As far as I can tell, creating a function for the collection of subdocs is not supported by Mongoose.

I got around this by defining a method in topSchema that would do what I want.

wciu
  • 1,183
  • 2
  • 9
  • 24
  • Two years later, I'm looking to make a subdoc instance method that updates the subdoc. Do you know if this is possible? `this.save()` does not seem to work. See: http://stackoverflow.com/questions/29998323 – Antrikshy May 02 '15 at 04:25
  • Subdocs can't be saved, you need to save the parent. So this.parent().save() should work, but you will need to test it out. – wciu May 04 '15 at 15:29
  • I have since refactored, but now I'll try this. If it works I'll let you know and you can post it as an answer. Looks promising. Thanks! – Antrikshy May 04 '15 at 15:38