首页 > 解决方案 > 如何稳健地搜索包含对象嵌套数组的集合

问题描述

我有一组包含嵌套数组的装置。我希望能够进行稳健的搜索。这是我的模型和下面的代码。谢谢

const team = {
  ref: 'TeamModel',
  type: Array,
  name: {
    type: String,
    enum: ['AFC Bournemouth', 'Arsenal', 'Aston Villa', 'Brighton & Hove Albion', 'Burnley', 'Chelsea',
      'Crystal Palace', 'Everton', 'Leicester City', 'Liverpool', 'Manchester City', 'Manchester United',
      'Newcastle United', ' Norwich City', 'Sheffield United', 'Southampton', 'Tottenham Hotspur', 'Watford',
      'West Ham United', 'Wolverhampton Wanderers']
  },
  score: { type: Number, default: 0 }
};

const fixtureSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  teamA: team,
  teamB: team,
  status: { type: String, default: 'pending' },
  matchInfo: {
    type: Array,
    date: Date,
    stadium: {
      type: String,
      enum: ['Vitality Stadium', 'The Amex', 'Turf Moor', 'Cardiff City Stadium',
        "John Smith's Stadium", 'King Power Stadium', 'Goodison Park', 'Anfield',
        'Emirates Stadium', 'Stamford Bridge', 'Selhurst Park', 'Craven Cottage',
        'Wembley Stadium', 'London Stadium', 'Etihad Stadium', 'Old Trafford',
        'St James Park', "St Mary's Stadium", 'Vicarage Road', 'Molineux Stadium']
    }
  },
  createdAt: { type: Date, default: moment(Date.now()).format('LLLL') },
  updatedAt: { type: Date, default: moment(Date.now()).format('LLLL') },
});
    const {
      name, date, stadium, status, score
    } = req.body;
    try {
      if (name || date || stadium || status) {
        const fixture = await FixtureModel.find({
          $or: [
            { status },
            { teamA: { name, score } },
            { teamB: { name, score } },
            { matchInfo: { $elemMatch: { date, stadium } } },
          ]
        })
          .exec();
        if (fixture.length <= 0) {
          return response(res, 404, 'error', {
            message: messages.fixtureNotFound
          });
        }
        return response(res, 200, 'success', {
          fixture
        });
      }
    } catch (error) {
      console.log(error);
      return response(res, 400, 'error', {
        message: messages.error
      });
    }
  }

在我目前的实现中,只有带有状态的搜索才有效。尽管集合中有匹配参数,但与其他人一起搜索会返回一个空对象。

状态:可以是['completed', 'pending'] 体育场:可以是['Vitality Stadium', 'The Amex', 'Turf Moor', 'Cardiff City Stadium', "John Smith's Stadium", 'King Power Stadium', 'Goodison Park', 'Anfield', 'Emirates Stadium', 'Stamford Bridge', 'Selhurst Park', 'Craven Cottage'...]

这是回购分支。该功能在线297

标签: arraysnode.jsmongodbexpressmongoose

解决方案


推荐阅读