【问题标题】:How to use async find method in mongoose?如何在猫鼬中使用异步查找方法?
【发布时间】:2018-02-27 16:08:12
【问题描述】:

这是我目前用 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;
  });
});

【问题讨论】:

  • username = user.username 的目的是什么?
  • 是的,我需要获取用户名。
  • 您是否希望在const username = ''; 中定义的相同标识符username 被分配给username = user.username;
  • 是的,我需要这样做。

标签: javascript node.js mongoose


【解决方案1】:

你可以从.findOne()函数returnuser.username。请注意,使用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;
  });
});

【讨论】:

    猜你喜欢
    • 2020-08-30
    • 2020-03-06
    • 2023-04-08
    • 2021-08-03
    • 2020-08-01
    • 1970-01-01
    • 2012-01-03
    • 2021-04-19
    • 2012-06-24
    相关资源
    最近更新 更多