简体   繁体   中英

GET an object from mongodb using mongoose

The problem is probably simple, but my 2 AM brain can't understand what's going on anymore. I'm trying to create a profile page that shows basic public info. The way I'm trying to make it work is pulling out the users username from mongodb when registered the account by his specific _id. If needed, verification I use is JWT.

app.post('/api/user-profile', async (req,res) => {
  const { token } = req.body

  if(!token) {
      return res.json({ status: 'error', error: 'not logged in' })
  }

  try {
      const user = jwt.verify(token, JWT_SECRET)
      const userid = user.id
   
      const result = User.findOne({ userid })

      console.log(result)
      // return res.json({ status: 'ok', name: result })
  } catch(error) {
      // return res.json({ status: 'error', error: 'something went wrong' })
      console.log(error)
  }
})

I'm not sure what function should I use, findOne() or findById() . I tried to look at the documentation at mongoose, but the explanation is a bit too hard for me to understand.

PS User = the user registration model. If needed I can paste in the code.

I don't have a lot of experience with mongoose but worked with Mongo quite a lot. findOne is a direct correspondent of Mongo's findOne function which receives a query in the format {"key": "expectedValue"}. If you want to use it to get data by id the query is {"_id": user.id}.

Because fetching data by id is a common case, the lib added the method findByID which receives an ID, and then formats the query and makes an internal call to findOne.

use findById instead of findOne if userid is _id and use await before the query, so do like this:

const result = await User.findById(userid)

if you want to use findOne:

const result = await User.findOne({"_id" : userid})

if you want a plain object javascript use .toObject after query like this:

const result = await User.findById(userid).toObject()
console.log(result)

For anyone interested, the answer is just like Mohammad Yaser Ahmadi said. Everything works fine, and by getting the username I did:

const user = jwt.verify(token, JWT_SECRET)
const userid = user.id

const result = await User.findById(userid)

const usersName = result.username

console.log(usersName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM