Search code examples
javascriptnode.jsmongoosemongoose-schemamongoose-populate

How to add to a new collection from an existing collection


So I am creating a music Player and would like to create an Album Schema from a Song Schema(Already created).

In the Album Schema there is an album title and an array of songs. Now I would like to add the songs to the album if they have the same title.

How do I achieve this?

I have sorted the song collection by album title, but have no clue as how to add the songs to the songs array, if they have the same album title.

//This is the song Schema.
var Song = mongoose.model('Songs', {
    album: String,
    title: String,
    artist: String,
    genre: String,
    year: Number,
    src: String
});

//This is the Album Schema.
const AlbumSchema = new Schema({
    album: String,
    songs: [{
        title: String,
        artist: String,
        genre: String,
        year: Number,
        src: String
    }]
});

Also is there a way to nest Songs schema in Album schema?


Solution

  • //Blank Array which stores AlbumSchemaObject
    let AlbumSchemaArray = [];
    //sample Object
    let albumObj = {album:"abc",songs:[{title:"abc",artist:"abc",genre:"abc",year:"abc",src:"abc"}]}
    //Data from Database
    let dataFromMongo = someAlbumObj
    //search in already stored Array Object
    //if album names exists then fetch that Object
    var searchedAlbumObj = AlbumSchemaArray.find((singleObj) => {
                    return singleObj.album  === dataFromMongo.album;
                });
    //If object match then push songs in that objet
    if(typeof(searchedAlbumObj.album) != "undefined")
    {
        searchedAlbumObj['songs'].push(dataFromMongo.songs)
    }
    else //creates new object and stores
    {
        AlbumSchemaArray.push(dataFromMongo)
    }
    

    I have used find method to check object assigned or not. if not we will create new object and push it in one array if exists, we will fetch that object and push songs to that. hope this will help