Can you define an instance method for supporting documents in Mongoose?

If I have a schema in Mongoose that is defined as:

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 a supporting document? I tried the following (added before the model declaration), but it does not work:

 subSchema.methods.someFn = function() { return 'blah'; }; 
+6
source share
1 answer

Answering my own question.

What I originally wanted to do was create a function that can be used in a collection of subdomains, for example:

 topdoc.subs.someFn(); 

However, what I really did with the code in the original question was to create a function for the subdoc itself, for example:

 topdoc.subs[i].someFn(); 

It works.

As far as I can tell, creating a function to collect pallets is not supported by Mongoose.

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

+3
source

All Articles