0

考虑一张包含许多歌曲的专辑。我将专辑模式定义为将歌曲作为子文档。

但我不确定我们如何为子文档创建实例方法。

考虑如下架构:

// 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

我可以知道我们如何在子文档上实现实例方法吗?

4

0 回答 0