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

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

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中,如下所示:

  1. exports.create = async (req, res) => {
  2. const password = await hash(req.body.password);
  3. const rawUser = {
  4. ...req.body,
  5. password,
  6. };
  7. try {
  8. const user = await User.create(rawUser);
  9. const newUser = user.toObject();
  10. res.send(newUser);
  11. } catch (err) {
  12. if (err.code === 11000) {
  13. res.status(400).send({ message: 'A user with this email address has already registered.' });
  14. } else {
  15. res.status(500).send({ message: 'An unexpected error occurred' });
  16. }
  17. }
  18. };

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

英文:

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 -->

  1. const express = require(&quot;express&quot;)
  2. const router = express.Router();
  3. const controller = require(&quot;./controller&quot;)
  4. router.post(&quot;/signup&quot;, controller.create);
  5. module.exports = router;

<!-- end snippet -->

and this is my model file

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

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

  1. const mongoose = require(&#39;mongoose&#39;);
  2. const User = new mongoose.Schema(
  3. {
  4. firstName: {
  5. type: String,
  6. required: true
  7. },
  8. lastName: {
  9. type: String,
  10. required: true
  11. },
  12. picture: {
  13. type: String
  14. },
  15. password: {
  16. type: String,
  17. select: false
  18. },
  19. email: {
  20. required: true,
  21. type: String,
  22. unique: true
  23. }
  24. },
  25. {
  26. timestamps: true
  27. }
  28. );
  29. User.index({
  30. firstName: &#39;text&#39;,
  31. lastName: &#39;text&#39;,
  32. });
  33. 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 -->

  1. const User = require(&#39;./model&#39;);
  2. const { hash, compareHash } = require(&#39;../lib/util&#39;);
  3. const { createToken, findUserByToken } = require(&#39;../lib/auth&#39;);
  4. const cookieIsSecure = process.env.ENVIRONMENT === &#39;production&#39;;
  5. exports.create = async (req, res) =&gt; {
  6. const password = await hash(req.body.password);
  7. const rawUser = {
  8. ...req.body,
  9. password,
  10. };
  11. User.create(rawUser)
  12. .then(async user =&gt; {
  13. return user.save();
  14. })
  15. .then(async user =&gt; {
  16. const newUser = user.toObject();
  17. res.send(newUser);
  18. })
  19. .catch(err =&gt; {
  20. if (err.code === 11000) {
  21. res.status(400).send({ message: &#39;A user with this email address has already registered.&#39; });
  22. return;
  23. }
  24. res.status(500).send({ message: &#39;An unexpected error occurred&#39; });
  25. });
  26. };

<!-- 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:

  1. const rawUser = new User({ ...req.body, password});
  2. try {
  3. await rawUser.save();
  4. res.status(201).send(newUser);
  5. } catch(err) {
  6. if (err.code === 11000) return res.status(400).send({ message: '此电子邮件地址的用户已经注册过了。' });
  7. res.status(500).send({ message: '发生了意外错误' });
  8. }
英文:

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:

  1. const rawUser = new User({ ...req.body, password});
  2. try {
  3. await rawUser.save();
  4. res.status(201).send(newUser);
  5. } catch(err) {
  6. if (err.code === 11000) return res.status(400).send({ message: &#39;A user with this email address has already registered.&#39; });
  7. res.status(500).send({ message: &#39;An unexpected error occurred&#39; });
  8. }

答案2

得分: 1

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

  1. exports.create = async (req, res) => {
  2. try {
  3. const password = await hash(req.body.password);
  4. const rawUser = {
  5. ...req.body,
  6. password
  7. };
  8. const user = await User.create(rawUser);
  9. const newUser = user.toObject();
  10. res.send(newUser);
  11. } catch (err) {
  12. console.log("ERROR: ", err);
  13. if (err.code === 11000) {
  14. return res.status(400).send({
  15. message: "A user with this email address has already registered."
  16. });
  17. }
  18. res.status(500).send({ message: "An unexpected error occurred" });
  19. }
  20. };
英文:

You need to use async/await like this:

  1. exports.create = async (req, res) =&gt; {
  2. try {
  3. const password = await hash(req.body.password);
  4. const rawUser = {
  5. ...req.body,
  6. password
  7. };
  8. const user = await User.create(rawUser);
  9. const newUser = user.toObject();
  10. res.send(newUser);
  11. } catch (err) {
  12. console.log(&quot;ERROR: &quot;, err);
  13. if (err.code === 11000) {
  14. return res.status(400).send({
  15. message: &quot;A user with this email address has already registered.&quot;
  16. });
  17. }
  18. res.status(500).send({ message: &quot;An unexpected error occurred&quot; });
  19. }
  20. };

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:

确定