I am trying to create a doc to model with mongoose but model.create() does not return any promise

huangapple go评论81阅读模式
英文:

I am trying to create a doc to model with mongoose but model.create() does not return any promise

问题

代码中的问题似乎在于model.create()方法未返回任何Promise,导致无法处理。这可能导致了始终返回500错误,而不提供具体的错误信息。要解决此问题,您可以尝试将model.create()包装在一个Promise中,如下所示:

exports.create = async (req, res) => {
  const password = await hash(req.body.password);
  const rawUser = {
    ...req.body,
    password,
  };

  try {
    const user = await User.create(rawUser);
    const newUser = user.toObject();
    res.send(newUser);
  } catch (err) {
    if (err.code === 11000) {
      res.status(400).send({ message: 'A user with this email address has already registered.' });
    } else {
      res.status(500).send({ message: 'An unexpected error occurred' });
    }
  }
};

通过这种方式,您可以更好地处理错误并获得更具体的错误信息。

英文:

it seems that the create method does not return any promise that then can handle
I tried different things but nothing worked
this is my routes file

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const express = require(&quot;express&quot;)
const router = express.Router();


const controller = require(&quot;./controller&quot;)

router.post(&quot;/signup&quot;, controller.create);
 

module.exports = router;

<!-- end snippet -->

and this is my model file

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const mongoose = require(&#39;mongoose&#39;);

const User = new mongoose.Schema(
  {
    firstName: {
      type: String,
      required: true
    },
    lastName: {
      type: String,
      required: true
    },
    
    picture: {
      type: String
    },
    password: {
      type: String,
      select: false
    },
    email: {
      required: true,
      type: String,
      unique: true
    }
  },
  {
    timestamps: true
  }
);

User.index({
  firstName: &#39;text&#39;,
  lastName: &#39;text&#39;,
});

module.exports = mongoose.model(&#39;User&#39;, User);

<!-- end snippet -->

and this is the controller file

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const User = require(&#39;./model&#39;);
const { hash, compareHash } = require(&#39;../lib/util&#39;);
const { createToken, findUserByToken } = require(&#39;../lib/auth&#39;);

const cookieIsSecure = process.env.ENVIRONMENT === &#39;production&#39;;

exports.create = async (req, res) =&gt; {
  const password = await hash(req.body.password);
  const rawUser = {
    ...req.body,
    password,
  };
  
  User.create(rawUser)
    .then(async user =&gt; {
       return user.save();
    })
    .then(async user =&gt; {
      const newUser = user.toObject();
      res.send(newUser);
    })
    .catch(err =&gt; {
      if (err.code === 11000) {
        res.status(400).send({ message: &#39;A user with this email address has already registered.&#39; });
        return;
      }
      res.status(500).send({ message: &#39;An unexpected error occurred&#39; });
    });
};

<!-- end snippet -->

it always return the 500 error "an unexpected error occurred"
which is not really specific. and i do not know what is the problem exactly. but I am sure it has something to do with the model.create() it does not return any promise.

答案1

得分: 2

这里你混合了方法。 create 方法不需要 save,因为它是隐式的:

https://mongoosejs.com/docs/api.html#model_Model.create

请尝试这样做,我已经对你的代码进行了一些重构,并添加了更容易阅读和使用的 try/catch:

const rawUser = new User({ ...req.body, password});

try {
  await rawUser.save();
  res.status(201).send(newUser);
} catch(err) {
  if (err.code === 11000) return res.status(400).send({ message: '此电子邮件地址的用户已经注册过了。' });
  res.status(500).send({ message: '发生了意外错误' });  
}
英文:

Here you are mixing methods. create doesn't want save in it as it's implicit:

https://mongoosejs.com/docs/api.html#model_Model.create

Please try this, I've refactored your code a bit and added much easier to read and use try/catch:

const rawUser = new User({ ...req.body, password});

try {
  await rawUser.save();
  res.status(201).send(newUser);
} catch(err) {
  if (err.code === 11000) return res.status(400).send({ message: &#39;A user with this email address has already registered.&#39; });
  res.status(500).send({ message: &#39;An unexpected error occurred&#39; });  
}

答案2

得分: 1

你需要像这样使用 async/await:

exports.create = async (req, res) => {
  try {
    const password = await hash(req.body.password);
    const rawUser = {
      ...req.body,
      password
    };

    const user = await User.create(rawUser);
    const newUser = user.toObject();
    res.send(newUser);
  } catch (err) {
    console.log("ERROR: ", err);
    if (err.code === 11000) {
      return res.status(400).send({
        message: "A user with this email address has already registered."
      });
    }
    res.status(500).send({ message: "An unexpected error occurred" });
  }
};
英文:

You need to use async/await like this:

exports.create = async (req, res) =&gt; {
  try {
    const password = await hash(req.body.password);
    const rawUser = {
      ...req.body,
      password
    };

    const user = await User.create(rawUser);
    const newUser = user.toObject();
    res.send(newUser);
  } catch (err) {
    console.log(&quot;ERROR: &quot;, err);
    if (err.code === 11000) {
      return res.status(400).send({
        message: &quot;A user with this email address has already registered.&quot;
      });
    }
    res.status(500).send({ message: &quot;An unexpected error occurred&quot; });
  }
};

huangapple
  • 本文由 发表于 2020年1月3日 22:26:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580266.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定