考虑一张有很多歌曲的专辑。我将Album模式定义为将Songs作为subdocs。
但我不确定如何为子文档创建实例方法。
考虑以下架构:
// 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
我是否知道如何在Sub Documents上实现实例方法?