如何检查对象的字段是否与JS中的特定值匹配

时间:2018-05-29 02:55:43

标签: javascript node.js mongodb mongoose

我有两个模型,游戏和用户。游戏模型是

const GameSchema = new Schema({
  date: String,
  time: String,
  duration: Number, // minutes
  location: [{ type: Schema.Types.ObjectId, ref: 'Court' }],
  players_needed: Number,
  max_players: Number,
  level: Number,
  players_list: [{ type: Schema.Types.ObjectId, ref: 'User' }], // players_list: [{ type: String }],
  players_status: [{ playerId: String, status: String }], // status -joined or evaluted
  postGameEvaluation: [{ playerId: String, evaluations: { } }],
  author: { type: Schema.Types.ObjectId, ref: 'User' },
});

和用户模型是

const UserSchema = new Schema({
  email: { type: String, unique: true, lowercase: true },
  password: { type: String },
  handle: { type: String }, //   handle: { type: String, unique: true, lowercase: true },
  games: [{ type: Schema.Types.ObjectId, ref: 'Post' }], // games and status
});

我正在尝试使用此

检查用户是否已经在游戏的players_list中
  if (req.body.players_list.filter((e) => { return e._id === req.user._id; }).length > 0) {
.....

但是,即使用户已经在游戏中,if语句也无法检查它。例如,以下是一个Game和User对象的两个实例,其中if语句失败。这是游戏对象

{ location: [],
  players_list:
   [ { games: [],
       _id: '5b0cb9ff4a9c6a536d075f48',
       email: 'efafesfse',
       password: '$2a$10$bo1q0udXhL5ZnA9PMUZX4ufR0w0tcL5TmDARqAT5RpqfXheVtK3v2',
       handle: 'FSEFSEFSE',
       __v: 0,
       id: '5b0cb9ff4a9c6a536d075f48' },
     { games: [Array],
       _id: '5b0cba164a9c6a536d075f4b',
       email: 'poi',
       password: '$2a$10$sk.d5npeUMz0H9aQ6TKVzOir1j54UuXtdtQPIrxbKkwzPP07ODW/y',
       handle: 'POI',
       __v: 0,
       id: '5b0cba164a9c6a536d075f4b' },
     { games: [Array],
       _id: '5b0cba164a9c6a536d075f4b',
       email: 'poi',
       password: '$2a$10$sk.d5npeUMz0H9aQ6TKVzOir1j54UuXtdtQPIrxbKkwzPP07ODW/y',
       handle: 'POI',
       __v: 0,
       id: '5b0cba164a9c6a536d075f4b' },
     { games: [Array],
       _id: '5b0cbcd74a9c6a536d075f4e',
       email: 'bv',
       password: '$2a$10$BTvyzp9EnauZkODsg5010e/OUafNmjRbmAvJ33RslHbT.qiWTY4WC',
       handle: 'BV',
       __v: 0,
       id: '5b0cbcd74a9c6a536d075f4e' } ],
  _id: '5b0cba094a9c6a536d075f49',
  players_status:
   [ { _id: '5b0cba094a9c6a536d075f4a',
       playerId: '5b0cb9ff4a9c6a536d075f48',
       status: 'Joined' } ],
  postGameEvaluation: [],
  date: 'VVVVV',
  time: 'VVVVVVV',
  duration: 4,
  players_needed: 4,
  max_players: 4,
  level: 4,
  author:
   { games: [],
     _id: '5b0cb9ff4a9c6a536d075f48',
     email: 'efafesfse',
     password: '$2a$10$bo1q0udXhL5ZnA9PMUZX4ufR0w0tcL5TmDARqAT5RpqfXheVtK3v2',
     handle: 'FSEFSEFSE',
     __v: 0,
     id: '5b0cb9ff4a9c6a536d075f48' },
  __v: 0 }

以下是已经在游戏的players_list中的User对象,但if语句未能检查它

{ games: [ 5b0cba094a9c6a536d075f49 ],
  _id: 5b0cbcd74a9c6a536d075f4e,
  email: 'bv',
  password: '$2a$10$BTvyzp9EnauZkODsg5010e/OUafNmjRbmAvJ33RslHbT.qiWTY4WC',
  handle: 'BV',
  __v: 0 }

0 个答案:

没有答案