简体   繁体   English

我正在尝试创建一个文档来使用 mongoose 进行建模,但是 model.create() 没有返回任何承诺

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

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似乎 create 方法没有返回任何可以处理的承诺我尝试了不同的事情但没有任何效果这是我的路由文件

 const express = require("express") const router = express.Router(); const controller = require("./controller") router.post("/signup", controller.create); module.exports = router;

and this is my model file这是我的模型文件

 const mongoose = require('mongoose'); 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: 'text', lastName: 'text', }); module.exports = mongoose.model('User', User);

and this is the controller file这是控制器文件

 const User = require('./model'); const { hash, compareHash } = require('../lib/util'); const { createToken, findUserByToken } = require('../lib/auth'); const cookieIsSecure = process.env.ENVIRONMENT === 'production'; exports.create = async (req, res) => { const password = await hash(req.body.password); const rawUser = { ...req.body, password, }; User.create(rawUser) .then(async user => { return user.save(); }) .then(async user => { 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.' }); return; } res.status(500).send({ message: 'An unexpected error occurred' }); }); };

it always return the 500 error "an unexpected error occurred" which is not really specific.它总是返回 500 错误“发生意外错误”,这并不是很具体。 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.但我确信它与 model.create() 有关系,它不会返回任何承诺。

Here you are mixing methods.这里是混合方法。 create doesn't want save in it as it's implicit: create不想save在其中,因为它是隐式的:

https://mongoosejs.com/docs/api.html#model_Model.create 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:请试试这个,我已经重构了你的代码,并增加了更容易阅读和使用 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: '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:您需要像这样使用 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" });
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM