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';
};
In Mongoose, subdocuments are documents that are nested in other documents. You can spot a subdocument when a schema is nested in another schema. Note: MongoDB calls subdocuments embedded documents.
methods are defined on the document (instance). You might use a static method like Animal.findByName : const fido = await Animal. findByName('fido'); // fido => { name: 'fido', type: 'dog' } And you might use an instance method like fido.findSimilarTypes : const dogs = await fido.
A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
Subdocuments are documents embedded in other documents. In Mongoose, this means you can nest schemas in other schemas. Mongoose has two distinct notions of subdocuments: arrays of subdocuments and single nested subdocuments.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With