简体   繁体   中英

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

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

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: '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) => {
  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" });
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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