lemooljiang avatar

Mongodb数据库遍历 / 网络研习社#85

lemooljiang

Published: 12 Sept 2023 › Updated: 12 Sept 2023Mongodb数据库遍历 / 网络研习社#85

Mongodb数据库遍历 / 网络研习社#85

mongodb.jpg

https://www.mongodb.com/

Mongodb是个简单易用、拓展性极强的数据库。对它的查询和遍历说不上难,但也有些技巧在的。

条件查询

//增加查找条件
or() 
limit(1) 
sort()   
skip()
User.find()//查询全部
  .or([{gender:2}])//查询gender为2的数据
  .sort({_id:'desc'})//倒序排列数据, 或sort({_id: -1}),asc正序  
  .limit(2)//展示两条
  .skip(2)//跳过前两个

eg:
let images = await User
     .find({user_id: req.user_id})
     .sort({_id:'desc'})
     .limit(50)

对数据库遍历

// nodejs端
//查询用户
app.get('/getusers/:skip', async (req, res) => {
  try {
    let limit = 5
    let skip = req.params.skip
    // 主要是通过limit和skip来进行遍历
    // limit 和 skip 要保持一致
    let users= await User
      .find()
      .sort({_id:'desc'})
      .limit(limit)
      .skip(skip)
    res.status(200).send({
      users
    })

  } catch (err) {
      console.error(556, err)
      res.status(500).send('Something went wrong');
  }
})

// nuxt前端
let skip = 5
let skipNum = ref(0)
//获取用户
const getHistory = async () => { 
  const getOption = {
    method: "GET",
    baseURL
  }
  let { data,  error } =  await useFetch('/getusers/0', getOption)
  console.log(668, data.value.users)
}

if(process.client){
  getHistory()
}

const more = async () => {
  console.log(563, "skipNum", skipNum.value)
  const getOption = {
    method: "GET",
    baseURL
  }
  skipNum.value += skip
  let { data,  error } =  await useFetch('/getusers/'+skipNum.value, getOption)
  if(error.value) {
    message.error("失败!\n"+error.value.data, { duration: 5e3 })
    return
  }
  if(data.value.users.length < skip){
    console.log("没有更多数据了!")
    moreFlag.value = false
  }
}

这个遍历有点像接力赛,查完一段再查下一段。通过limit和skip来完成一段段的查询,效果还是很完美的。

Leave Mongodb数据库遍历 / 网络研习社#85 to:

Written by

Designer , Poet , Technology enthusiasts

Read more #cn posts


Best Posts From lemooljiang

We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From lemooljiang