Design

Design
asp.net mvc

2019年11月7日 星期四

[紀錄]nodejs Mongodb分頁模糊查詢

 
app.post('/api/video', function (req, res) {
  try {
    var PageSize = req.body.PageSize;
    var PageIndex = req.body.PageIndex;
    if (!PageSize || !PageIndex) {
      return;
    }

    var Search = {};
    if (req.body.Search) {
      Search = {
        'name': {
          $regex: `^.*${req.body.Search}.*`,
          $options: 'i'
        }
      }
    }
    var dbo = client.db("db");

    dbo.collection('video').find(Search).sort({
      upload_at: -1
    }).skip(PageSize * PageIndex - PageSize).limit(PageSize).toArray((err, items) => {
      if (err) {
        console.log(err)
        throw err;
      }
      dbo.collection('video').countDocuments(Search, function (err, count) {
        res.end(JSON.stringify({
          "result": items,
          "pageCount": Math.ceil(count / PageSize),
          "videoCount": count,
        }));
      client.close();
      })
    });
  } catch (e) {
    console.error(e);
  }
});

沒有留言:

張貼留言