Mongoose中的匹配查询对于数组不起作用

时间:2017-03-09 13:40:44

标签: node.js mongodb mongoose mongodb-query aggregation-framework

您可以在下面找到我的代码,我尝试从以下任何列表中的所有已授权用户的用户中排除:friends,sentFriendRequests和receiveFriendRequests。不幸的是,代码不起作用(其他条件工作正常,例如按id,fullName和email过滤),但我无法弄清楚原因。提前感谢您的任何帮助。

User.findOne({_id: req.user.id})
  .exec(function (err, user) {
    if (err) {
      logger.error('Friend 500 ' + err)
      return res.status(500).json({
        code: config.errorCode.status500.code,
        message: config.errorCode.status500.message
      })
    }
    console.log('User id: ' + user._id)
    User.aggregate([
      {
        $project: {
          fullName: {
            $concat: ['$firstName', ' ', '$lastName']
          },
          email: 1,
          avatarPath: 1,
          mutualFriends: {
            $size: {
              $setIntersection: [user.friends, '$friends']
            }
          }
        }
      },
      {
        $match: {
          $and: [
            {
              _id: { $ne: user._id }
            },
            {
              $or: [

                {
                  fullName: { $regex: req.query.keyWord, $options: 'i'}
                },
                {
                  email: { $regex: req.query.keyWord, $options: 'i'}
                }
              ]
            },
            {
              friends: { $ne: user._id }
            },
            {
              receivedFriendRequests: { $ne: user._id }
            },
            {
              sentFriendRequests: { $ne: user._id }
            }
          ]
        }
      },
      { $sort: { mutualFriends: -1} }
    ])
      .exec(function (err, result) {
        if (err) {
          logger.error('Friend 500 ' + err)
          return res.status(500).json({
            code: config.errorCode.status500.code,
            message: config.errorCode.status500.message
          })
        }

        return res.json({
          data: result
        })
      })
  })

架构定义

var UserSchema = new Schema({
  firstName: {
    type: String
  },
  frstNameNormalized: {
    type: String
  },
  lastName: {
    type: String
  },
  lastNameNormalized: {
    type: String
  },
  email: {
    type: String,
    // unique: true,
    // required: true,
    lowercase: true,
  // match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please enter a valid email address']
  },
  birthDate: {
    type: Date
  },
  facebookID: {
    type: String
  },
  twitterID: {
    type: String
  },
  password: {
    type: String
  },
  nickname: {
    type: String,
    default: ''
  },
  description: {
    type: String,
    default: ''
  },
  avatarPath: {
    type: String,
    default: ''
  },
  friends: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  receivedFriendRequests: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  sentFriendRequests: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  sharedFriendCheckIns: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  resetPasswordToken: String,
  resetPasswordExpires: Date,
  emailConfirmToken: String,
  emailConfirmExpires: Date,
  emailConfirmed: {
    type: Boolean,
    default: false
  }
})
....
var User = module.exports = mongoose.model('User', UserSchema)

可以在以下link找到完整的模型说明。 MongoDB版本是v3.2.8

1 个答案:

答案 0 :(得分:1)

如果有人需要,我已经解决了这个问题。由于我是初学者,因此解决方案很简单,可能不是最佳解决方案,但它可以做到应有的目标。

FriendController.route('/find')
.get(passport.authenticate('jwt', { session: false }), function (req, res) {

// get users who are not firends of authorized user nor he/she send to them friend request or received it

var parts = (req.query.keyWord).split(' ')
var firstName = ''
var lastName = ''

if (parts.length > 1) {

  firstName = (req.query.keyWord).split(' ').slice(0, -1).join(' ')
  lastName = (req.query.keyWord).split(' ').slice(-1).join(' ')

} else {

  firstName = req.query.keyWord
  lastName = req.query.keyWord

}

User.findOne({_id: req.user.id})
  .exec(function (err, user) {
    if (err) {
      logger.error('Friend 500 ' + err)
      return res.status(500).json({
        code: config.errorCode.status500.code,
        message: config.errorCode.status500.message
      })
    }

    User.find({
      _id: { $ne: user.id },
      friends: { $ne: user.id },
      receivedFriendRequests: { $ne: user.id },
      sentFriendRequests: { $ne: user.id },
      $or: [
        {
          firstName: { $regex: firstName, $options: 'i'}
        },
        {
          lastName: { $regex: lastName, $options: 'i'}
        },
        {
          email: req.query.keyWord
        }
      ]

    })
      .select('_id')
      .exec(function (err, potentialFriends) {
        if (err) {
          logger.error('Friend 500 ' + err)
          return res.status(500).json({
            code: config.errorCode.status500.code,
            message: config.errorCode.status500.message
          })
        }

        var ids = potentialFriends.map(function (potentialFriend) {
          return potentialFriend._id
        })

        User.aggregate([
          {
            $project: {
              firstName: 1,
              lastName: 1,
              email: 1,
              avatarPath: 1,
              mutualFriends: {
                $size: {
                  $setIntersection: [user.friends, '$friends']
                }
              }
            }
          },
          {
            $match: {
              _id: { $in: ids }
            }

          },
          { $sort: { mutualFriends: -1} }
        ])
          .exec(function (err, result) {
            if (err) {
              logger.error('Friend 500 ' + err)
              return res.status(500).json({
                code: config.errorCode.status500.code,
                message: config.errorCode.status500.message
              })
            }
            return res.json({
              data: result
            })
          })
      })
  })
})