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?