0

I try to make a query with mongoose with this :

api.get('/', authenticate, async function (req, res) {
    let adminState = await isAdmin(req.user.id)
    if (adminState) {
      console.log("test 0")
      let query = User.find().sort('username', 1).skip(req.query.skip || 0).limit(req.query.limit || 20)
      console.log("test 1")
      try {
        var users = await query.exec()
      } catch (err) {
        res.status(500).json({ error: "..."})
      }
    } else {
      res.status(401).json({ error: '...'})
    }
  })

async function isAdmin(id) {
  var testAdmin = false
  currentUser = await User.findById(id)
  if (currentUser && currentUser.role === "Administrateur") {
    testAdmin = true
  }
  return testAdmin
}

However when in postman when I do a GET request to the following url : 'http://localhost:3000/api/users?skip=0&limit=10' my server print the console.log('test 0') and do not continue further with the console.log("test 1"). How could I fix this ?

Léo Coletta
  • 1,099
  • 2
  • 12
  • 24
  • Why are you mixing callbacks when you already have other calls with Promise's and `async/await`? Do you not realize that ALL Mongoose merhods return a promise which you can `await`? Does not look like you know that. – Neil Lunn May 14 '18 at 12:54
  • Basically, instead of doing `await User.findById(id, function (err, currentUser)` which actually does not do what you seem to think it does, what you instead do is `let currentUser = await User.findById(id)`. And so on for all the places you are making the same mistake in your code. Read the reference and understand how that works. – Neil Lunn May 14 '18 at 12:57
  • @NeilLunn I don't know that, thanks. However how do I check for errors ? – Léo Coletta May 14 '18 at 12:57
  • `try { } catch` blocks work just fine under `async/await`. Read the referenced answer. – Neil Lunn May 14 '18 at 12:58

0 Answers0