0

Consider an album that has many songs. I define the Album schema as such that it has the Songs as subdocs.

But I'm not sure how do we create instance method for subdocuments.

Consider the schema as below:

// Sub Document
var SongSchema = new mongoose.Schema({
    title           :   {type: String},
    artist          :   {type: String},
    genre           :   {type: String}
});

// Parent Document
var AlbumSchema = new mongoose.Schema({
    title           :   {type: String, required: true},
    composer        :   {type: String},
    songs           :   [songSchema],
});


AlbumSchema.methods.addSong = function(data) {
    var song = {
        title       : data.title,
        artist      : data.artist,
        genre       : data.genre
    }
    this.songs.push(song);
    return;
};


SongSchema.pre('validate', function(next) {
    // I would like to call the someFunction as below. 
    // But how do I achieve this?

    this.someFunction();        // Errors ??
});

SongSchema.methods.someFunction = function() {
    // Some function
};

var album = new Album ({
                            title: 'T1',
                            composer: 'C1'
                        });
album.addSong ({title: 'S1', artist: 'A1', genre: 'G1'});   // Success

May I know how do we achieve having instance method on Sub Documents?

Ananth
  • 767
  • 1
  • 7
  • 15
  • 2
    The same way you did with the `AlbumSchema`. Just make sure you access it on an instance of `Song` model. – Rodrigo Medeiros Jan 27 '15 at 12:54
  • Thanks.. I initially tried the same approach as `AlbumSchema`. But I noticed the collection named `songs` was created in MongoDB. I didn't wanted to have an orphan collection. But later I realized I was trying something with songs.save that causes the collection to be created. Is there a way we can create a mongoose model but restriction from creating a collection in Mongo? – Ananth Jan 27 '15 at 14:21
  • Mongoose creates a collection per schema. What you could do is to define your model as a Javascript object and embbed it into your `AlbumSchema`. I think [this question here](http://stackoverflow.com/q/28051860/2241993) can give you some idea of what I'm talking about. – Rodrigo Medeiros Jan 27 '15 at 16:18

0 Answers0