mardi 7 mai 2019

How do I query a map of subdocuments by a key in MongoDB?

I've created the following mongoose schema to save some music data that I pull from iTunes API:

...
const MusicAlbumSchema = new Schema({
  artist_name: {
    type: String,
    required: 'enter an artist name'
  },
  album_name: {
    type: String,
    required: 'enter an album name'
  },
  artwork_url: {
    type: String,
    required: 'enter an artwork url'
  }
});
const SearchResultSchema = new Schema({
  created_date: {
    type: Date,
    default: Date.now
  },
  search: {
    type: Map,
    of: [ MusicAlbumSchema ]
  }
});
...

search field in SearchResultSchema takes a search query as the key (e.g. 'The Beatles'), and stores the returned results as the array of subdocuments of MusicAlbumSchema. In order to test it, I tried to write some mocha tests:

...
  it('Creates a search result with sub-documents', done => {
    const musicAlbum1 = new MusicAlbum({
      artist_name: 'The Beatles',
      album_name: 'Abbey Road',
      artwork_url: 'www.google.com'
    });
    const musicAlbum2 = new MusicAlbum({
      artist_name: 'The Beatles',
      album_name: 'Let It Be',
      artwork_url: 'www.google.com'
    });

    const result = new SearchResult({
      search: {}
    });
    result.search.set('The Beatles', [musicAlbum1, musicAlbum2]);


    result.save().then(() => {
      SearchResult.findOne({
        'The Beatles' : { $exists : true }
      }).then(records => {
        console.log(records);
        assert(records.length === 2);
        done();
      });
    });
  });
...

What am I doing wrong and how do I properly query the saved data (particularly - search field in SearchResultSchema)?

Aucun commentaire:

Enregistrer un commentaire