Mongoose async / wait for Koa to get stuck waiting for Model.findOne (). Exec ()

I have a Koa 2 application, and this entry in / signup is processed by this function:

import User from 'models/user';

export const signup = async (ctx, next) => {
  const { email, password } = ctx.request.body;
  try {
    const existingUser = await User.findOne({ email });

    if (existingUser) {
      ctx.body = { error: 'Email is in use' };
      return next();
    }

    const user = new User({
      email,
      password,
    });
    await user.save();
    ctx.body = { success: true };
  } catch (e) {
    next(e);
  }
  return next();
};

The funtion function receives the correct data, but await User.findOne().exec();never returns or gets stuck.

I think the problem is that if I delete, the code runs fine. If I switch to Promise, how ... find().thenIt works too. async / await works either, because if I go to expect fetch () (to emulate async), it works ... but here is my babel configuration

{
  "presets" : ["latest", "stage-0"],
  "plugins": [
    ["module-resolver", {
      "root": ["./src"]
    }]
  ]
}

mongoose - version 4.7.0

+4
source share
2 answers

t. , . , ​​ .

0

, . promises ? , JS promisese Mongoose promises? mongoose promises , native JS:

const mongoose = require('mongoose');

mongoose.Promise = Promise; // Use native Promises

mongoose.connect(config.get('mongoose.uri'), config.get('mongoose.options'));
...
module.exports = mongoose;
0

Source: https://habr.com/ru/post/1662068/


All Articles