I'm testing sequelize for a new project, and I can't seem to be able to return my created instance, thanks for any help.
My create method :
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"});
}
And here's my model :
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;
How can i return my newUser instance after it's inserted in the database?
CodePudding user response:
You just create a function that will return user
in Promise but you never call it.
Try next:
Promise
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()});}
}
OR with 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);
}
CodePudding user response:
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" });
});
}
Do not use promises (.then
) with async await.