mongoose API

mongoose API

TOC

已User和Beacon數據模型爲例

const UserSchema = mongoose.Schema({
  username: {
    type: String,
    unique: true
  },
  passhash: String,
  nickname: String,
  fans: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }]
});

const Beacon = mongoose.Schema({
  location: {
    type: [Number, Number],
    index: '2d'
  }
});

查詢接口

方法有:
1. find
2. findOne
3. findById
4. aggregate

過濾(match)


/* 正則表達式過濾 */
  const match = {
    'nickname': {
      $regex: 'xxx'
    }
  };

/* 數組過濾 */
  const match = {
    'fans': {
      $in: [new ObjectId(xxxxxxx)]
    }
  }


  User
  .aggregate()
  .match(match);

選擇屬性(project, select)

可以指定需要的的屬性
還有更多的功能,例如:( 可以返回數組屬性的長度, 返回數組屬性的一部分)


  <!-- aggregate方法中 -->
    User.aggregate()
    .match({...})
    .project({
      nickname: 1,
      fansNumber: {
        $size: '$fans'
      }
    });

  <!-- find / findOne / findById方法中 -->
    const project = {
      'fans': $slice: [limit * page, limit * page + limit]
    }

    User.findOne({_id: new ObjectId(_id)},  project);
    // 或
    User.findOne({_id: new ObjectId(_id))
        .select('_id nickname fans');

將引用的數據集合填充到屬性中(populate)

  User
  .findById(_id, project)
  .populate('fans');

  //  引用user集合返回nickname字段
  User
  .findById(_id, project)
  .populate('fans', 'nickname');

平面座標區域過濾(goeWithin)

注意:緯度越上面越大,和canvas座標系相反

    const sw = [parseFloat(54.5345), parseFloat(54.3434)];
    const ne = [parseFloat(34.4343), parseFoat(43.3464)];

    cosnt match = {
      'location': {
        $geoWithin: {
          $box: [
            [sw[0], sw[1]],
            [ne[0], ne[1]]
          ]
        }
      }
    };

    Beacon.find(match);

平面座標區域距離排序(near)

  <!-- aggregate方法的實現方式 -->
  Share.aggregate([
     {
         $geoNear: {
             near: [543, 5435],
             distanceField: 'distance',
             maxDistance: (ne[0] - sw[0]),
             query: match,
             num: query.limit,
             uniqueDocs: true
         }
     }
  ]).exec();


  <!-- find方法的實現方式 -->
    const match = {
      location: {
        $near: [543, 5435], // 中心點
        $maxDistance: ne[1] - sw[1]
      }
    };

    Beacon.find(match);

修改接口

修改數據集合屬性

  <!-- 插入數據到數組屬性的指定位置 -->
    User.findByIdAndUpdate(_id, {
      $push: {
        fans: {
          $each: [_userId],
          $position: 0
        }
      }
    });

  <!-- 刪除數據從數組屬性的指定位置 -->
    User.findByIdAndUpdate(_id, {
      $pull: {
        fans: _userId
      }
    })    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章