如何 return 在 sequelize 中创建实例

How to return created instance in sequelize

我正在为一个新项目测试 sequelize,我似乎无法 return 我创建的实例,感谢您的帮助。

我的创建方法:

exports.create = (req, res) => {
    let user = {
        "username" : req.body.username,
        "email"    : req.body.email,
        "pseudo"   : req.body.pseudo,
        "password" : bcrypt.hashSync(req.body.password,10),
        "created_at" : sequelize.fn('NOW')
    };
   
    if (!user.username || !user.email) {
        res.status(201).send("username required!")
    }

    const newUser = async (user) => {
        await User.create(user)
        .then((data) => {return data;console.log(data);})
        .catch((e)=>{console.log(e)});}

    console.log(newUser); // this returns [AsyncFunction: newUser]
    res.status(200).send({"message" : "ok"});
    
}

这是我的模型:

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = require('../services/database_connection');
const validate = require('validator');

const User = sequelize.define('user',{
  id ,
  username ,
  email ,
  pseudo,
  password,
  created_at
}, {
  timestamps : false,
  freezeTableName : true,
});

module.exports = User;

如何 return 我的 newUser 实例插入数据库后?

您只是在 Promise 中创建了一个将 return user 的函数,但您从未调用它。 接下来试试:

承诺
exports.create = (req, res) => {
    let user = {
        "username" : req.body.username,
        "email"    : req.body.email,
        "pseudo"   : req.body.pseudo,
        "password" : bcrypt.hashSync(req.body.password,10),
        "created_at" : sequelize.fn('NOW')
    };
   
    if (!user.username || !user.email) {
        res.status(201).send("username required!")
    }

    User.create(user)
        .then((data) => { res.status(200).send(data)})
        .catch((e)=>{ console.log(e); res.status(500).end()});}        
}
或 async/await
exports.create = async (req, res) => {
    let user = {
        "username" : req.body.username,
        "email"    : req.body.email,
        "pseudo"   : req.body.pseudo,
        "password" : bcrypt.hashSync(req.body.password,10),
        "created_at" : sequelize.fn('NOW')
    };
   
    if (!user.username || !user.email) {
        res.status(201).send("username required!")
    }

    const newUser = await User.create(user);
    res.status(200).send(newUser);
}
exports.create = (req, res) => {
    let user = {
        "username": req.body.username,
        "email": req.body.email,
        "pseudo": req.body.pseudo,
        "password": bcrypt.hashSync(req.body.password, 10),
        "created_at": sequelize.fn('NOW')
    };

    if (!user.username || !user.email) {
        res.status(201).send("username required!")
    }

    User.create(user)
        .then((data) => {
            console.log(data);
            res.status(200).send({ "message": "ok" });
        })
        .catch((e) => {
            console.log(e);
            res.status(500).send({ "message": "Internal Server Error" });
        });

}

不要将承诺 (.then) 与异步等待一起使用。