6

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

Lucas Katayama
  • 4,445
  • 27
  • 34
  • Your code doesn't show you using `.exec()` (although it's probably not strictly necessary to use it). Also, are you sure that it doesn't throw an exception? Your code calls `next` twice when an exception occurs (once with the error argument, and then with `return next`). – robertklep Nov 27 '16 at 18:09
  • ah sorry .. copied an old code.. but doesn't work either... and no exceptions... and already fixed the two calls... thanks – Lucas Katayama Nov 27 '16 at 18:11

2 Answers2

0

I wrote very similar app, but all worked fine. What type of promises you use? I mean you use native JS promisese or Mongoose promises? With mongoose promises I had problems so I change it for 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;
Sergaros
  • 821
  • 1
  • 5
  • 14
0

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

Lucas Katayama
  • 4,445
  • 27
  • 34