Search code examples
node.jsmongooseasync-awaitbabeljskoa2

Mongoose async/await with Koa get stuck on await Model.findOne().exec()


I have an Koa 2 application, and a post to /signup is handled 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 receives correct data but the await User.findOne().exec(); never returns and gets stuck.

I think the problem is there because if I remove, code is executed normally. If I switch to Promise like... find().then It works too. async/await is working either, because If I change to a await fetch() (to emulate async) it works... but here is my babel config

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

mongoose is version 4.7.0


Solution

  • I started another application and t is working now. Don't know what happened. Maybe new version fixed.