2
I am creating an API with nodejs and Mongoose, I am trying to create a user using async await, but I did not succeed, whenever I send the data they are not saved, I already checked the entire connection with BD and everything, including I made this same code with Promise(then/catch) and worked, but with the async await, no
What’s wrong, and how it would look the right way?
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const Database = "mongodb://localhost:27017/ecommerce"
const userSchema = mongoose.Schema({
username: String,
email: String,
password: String,
isAdmin: {
type: Boolean,
default: false
}
});
const User = mongoose.model("user", userSchema);
exports.createNewUser = async (username, email, password) => {
try {
await mongoose.connect(Database)
const user = User.findOne({ email: email });
if (user) {
mongoose.disconnect();
throw new Error("Este e-mail já está em uso")
}
const nUser = new User({ username, email, password: bcrypt.hash(password, 10) });
nUser.save();
} catch (err) {
console.log(err)
}
}
Code (that works) with promises:
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const Database = "mongodb://localhost:27017/ecommerce"
const userSchema = mongoose.Schema({
username: String,
email: String,
password: String,
isAdmin: {
type: Boolean,
default: false
}
});
const User = mongoose.model("user", userSchema);
exports.createNewUser = (username, email, password) => {
return new Promise((resolve, reject) => {
mongoose
.connect(Database)
.then(() => {
return User.findOne({ email: email });
})
.then(user => {
if (user) {
mongoose.disconnect();
reject("Este e-mail já está em uso");
} else {
return bcrypt.hash(password, 10);
}
})
.then(hashedPassword => {
let user = new User({
username: username,
email: email,
password: hashedPassword
});
return user.save();
})
.then(() => {
mongoose.disconnect();
resolve();
})
.catch(err => {
mongoose.disconnect();
reject(err);
});
});
};
You put
await User.findOne({ email: email });
andawait nUser.save();
And yet it didn’t work? That’s it?– Cmte Cardeal
You can show the code with Promise that worked?
– Sergio
Sergio, there’s the code with Promises. And Yes, Cardel, I also tried what you said and it didn’t work either.
– Diego Oliveira