Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you define instance method for sub documents in Mongoose?

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';
};
like image 757
wciu Avatar asked Mar 14 '13 03:03

wciu


People also ask

Can a document have a sub document in MongoDB?

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.

What is instance method in Mongoose?

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.

What defines the structure of documents in Mongoose?

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.

What is a subdocument in Mongoose?

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.


1 Answers

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.

like image 199
wciu Avatar answered Oct 03 '22 11:10

wciu