当带有回调的findOno返回数据时,为什么等待schema.findOne返回null?]

问题描述 投票:0回答:1

我想从我的模式中接收数据,但是出现了一些奇怪的问题。

router.get('/validate/:key',  async ctx => {
  const { key } = ctx.params
  const userLock = { key }

  const user = await User.findOne({ userLock })

  if(user){
    ctx.session.userkey = key
  }
})

因此,对于'findOne',用户始终为null;如果只是'find',则用户为epmty数组。但是,如果在同一代码中使用回调,并在回调中记录“用户”,则可以正常工作并显示用户。如何解决?方案很常见:

 name: {
    type: String,
  },
  email: {
    type: String,
    unique: true,
  },
  password: {
    type: String,
    private: true,
  },
  userLock:{
     key: {
      type: String,
      default: nanoid(),
      unique: true,
    },
     date: {
      type: Date,
      default: Date.now,
    },
  }

我想从我的模式中接收数据,但是出现了一些奇怪的问题。 router.get('/ validate /:key',async ctx => {const {key} = ctx.params const userLock = {key} const user = ...

node.js mongoose async-await koa
1个回答
0
投票

findOne。默认是猫鼬的回调风格。如果要使用异步/等待,则需要将其转换为Promise。您可以执行.exec(),这将返回您的承诺。像这样的东西

© www.soinside.com 2019 - 2024. All rights reserved.