如何在mongoose中使用异步查找方法?

时间:2017-09-19 02:20:35

标签: javascript node.js mongoose

这是我目前使用express.js编写的代码。



const router = express.Router();

router.post('/', async (req, res) => {
 const username = '';
  await User.findOne({_id: req.body.id,}, (err, user) => {
  if (err) // how to process this part?
  username = user.username;
  });
});




1 个答案:

答案 0 :(得分:-1)

您可以return功能user.username .findOne()。请注意,无法重新分配使用const声明的变量标识符,请参阅Is it possible to delete a variable declared using const?

const router = express.Router();

router.post('/', async (req, res) => {
  const username = await User.findOne({_id: req.body.id,}, (err, user) => {
    // return empty string or other value if `err`
    if (err) return "" // how to process this part?
    return user.username;
  });
});