如何在MongoDB中通过键查询子文档映射?

时间:2019-05-07 22:29:33

标签: node.js mongodb testing mongoose mocha

我创建了以下猫鼬模式,以保存一些从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 ]
  }
});
...
SearchResultSchema中的

search字段将搜索查询作为关键字(例如“甲壳虫”),并将返回的结果存储为MusicAlbumSchema的子文档数组。为了对其进行测试,我尝试编写一些摩卡测试:

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

我在做什么错了,我该如何正确查询保存的数据(尤其是SearchResultSchema中的搜索字段)?

1 个答案:

答案 0 :(得分:0)

决定将我的架构更改为此:

const MusicAlbumSchema = new Schema({
  artist_name: {
    type: String,
    required: true
  },
  album_name: {
    type: String,
    required: true
  },
  artwork_url: {
    type: String,
    required: true
  }
});

const SearchResultSchema = new Schema({
  created_date: {
    type: Date,
    default: Date.now
  },
  search_query: {
    type: String,
    required: true,
    unique: true,
    dropDups: true
  },
  search_results: [MusicAlbumSchema]
});

–因此,摩卡测试也发生了变化:

  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_query: 'The Beatles',
      search_results: [musicAlbum1, musicAlbum2]
    });

    result.save().then(() => {
      SearchResult.findOne({
        search_query: 'The Beatles'
      }).then(record => {
        assert(record.search_results.length === 2);
        done();
      });
    });
  });