【问题标题】:How to add to a new collection from an existing collection如何从现有集合添加到新集合
【发布时间】:2019-09-03 00:27:42
【问题描述】:

所以我正在创建一个音乐播放器,并想从歌曲架构(已经创建)创建一个专辑架构。

在专辑架构中,有一个专辑标题和一组歌曲。现在,如果歌曲名称相同,我想将它们添加到专辑中。

我如何做到这一点?

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

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


    【解决方案1】:

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

    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' }
    
    
    

    【讨论】:

      【解决方案2】:

      根据您的架构设计,我得出的结论是,您计划仅使用一个模型(专辑收藏的“专辑”模型)。您已经为“歌曲”创建了一个模式。因此,不要在“专辑”集合中重复字段,而是在“专辑”模式中嵌套“歌曲”模式。 您可以按如下方式进行。

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

      【讨论】:

      • 谢谢巴拉特。但是,如果歌曲具有相同的专辑标题,我如何将歌曲从我的歌曲架构添加到专辑架构?我想在 Album Schema 的 Songs Array 中推送同一张专辑的歌曲。
      • 假设您有一个前端应用程序正在向专辑添加歌曲。当您添加一首新歌曲时,您将选择专辑。将相册的 _id 传递给后端。然后就可以进行上面的推送操作了。下面是完整的代码。我也会在答案中更新它 let newSong = {专辑:'xxx',标题:'xxx',艺术家:'xxx',流派:'xxx',年份:'xxx',src:'xxx'}专辑。更新({_id:专辑._id},{$push:{歌曲:newSong}});
      • @Bharath Op 想要添加“来自现有集合”
      【解决方案3】:
      //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 方法来检查是否分配了对象。如果不是,我们将创建新对象并将其推送到一个数组中 如果存在,我们将获取该对象并将歌曲推送到该对象。 希望这会有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-11
        • 1970-01-01
        • 2016-04-26
        • 2011-09-21
        • 2020-04-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多