如何从现有集合添加到新集合

问题描述 投票:0回答:3

所以我正在创建一个音乐播放器,并希望从一个歌曲模式(已经创建)创建一个专辑模式。

在Album Schema中有一个专辑标题和一系列歌曲。现在我想将这些歌曲添加到相册中,如果它们具有相同的标题。

我该如何实现这一目标?

我已按照专辑标题对歌曲集进行了排序,但如果他们有相同的专辑标题,则不知道如何将歌曲添加到歌曲数组中。

//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
    }]
});

还有一种方法可以在专辑架构中嵌套歌曲架构吗?

javascript node.js mongoose mongoose-schema mongoose-populate
3个回答
0
投票
//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)
}

我用find方法来检查是否分配了对象。如果不存在,我们将创建新对象并将其推送到一个数组(如果存在),我们将获取该对象并将歌曲推送到该对象。希望这会有所帮助


0
投票

从您的架构设计,我得出结论,您计划只使用一个模型(Album集合的'Album'模型)。您已经为“歌曲”创建了一个架构。因此,不要在“相册”集合中重复字段,而是将“歌曲”模式嵌套在“相册”模式中。你可以这样做。

const mongoose = require("mongoose");

var Song = mongoose.Schema('Songs', {
   album: String,
   title: String,
   artist: String,
   genre: String,
   year: Number,
  src: String
});

const AlbumSchema = new Schema({
   album: String,
   songs: [Song]
});

然后你就可以创建你的'相册模型'了,

const Album = module.exports = mongoose.model("Album", AlbumSchema);

然后无论在哪里(也许是控制器!)你想要创建一首新歌,你都可以这样做,

let newSong = {
    album: 'xxx',
    title: 'xxx',
    artist: 'xxx',
    genre: 'xxx',
    year: 'xxx',
    src: 'xxx'
}

Album.update(
    { _id: album._id },
    { $push: { songs: newSong } }
);

0
投票

如果您已经有一组歌曲,并且您需要查找特定专辑的歌曲,您可以使用:

Song.find({album: 'foo'})
  .exec()
  .then(songs => {
    return Album.findOneAndUpdate({album: 'foo'}, {$push: {songs: songs}})
      .exec()
  })
  .then(album => console.log(album))
  .catch(err => err);

您的相册架构应如下所示:

const AlbumSchema = new mongoose.Schema({
  album: String,
  songs: [songSchema]
});
const Song = mongoose.model('Song', songSchema);

例:

songs : [ { _id: 5cb05ecd0facc60f8e383259, album: 'foo', title: 'song1' },
  { _id: 5cb05ecd0facc60f8e38325a, album: 'bar', title: 'song2' },
  { _id: 5cb05ecd0facc60f8e38325b, album: 'foo', title: 'song3' } ]

Song.find({album: 'foo'})
  .exec()
  .then(songs => {
    return Album.findOneAndUpdate({album: 'foo'}, {$push: {songs: songs}})
      .exec()
  })
  .then(album => console.log(album))
  .catch(err => err);

// Code above gives you :

{ _id: 5cb05f8ee567df1092be74a9,
  songs: 
   [ { _id: 5cb05ee5f1a14c0fc23f0c4d,
       album: 'foo',
       title: 'song1',
       __v: 0 },
     { _id: 5cb05ee5f1a14c0fc23f0c4f,
       album: 'foo',
       title: 'song3',
       __v: 0 } ],
  __v: 0,
  album: 'foo' }


© www.soinside.com 2019 - 2024. All rights reserved.