Nodejs - Async await with Mongoose

Asked

Viewed 345 times

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);
            });
    });
};
  • 1

    You put await User.findOne({ email: email }); and await nUser.save(); And yet it didn’t work? That’s it?

  • 1

    You can show the code with Promise that worked?

  • Sergio, there’s the code with Promises. And Yes, Cardel, I also tried what you said and it didn’t work either.

1 answer

2


You are simply not using the await methods that return an interface Promise-like. Find out more about the await to actually know when to use it. In short, use it in methods that return a promise.

Thus, we missed using the await in the methods findOne, disconnect, bcrypt.hash and save.

Thus:

const bcrypt = require("bcrypt");
const mongoose = require("mongoose");

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) => {
    await mongoose.connect(Database);

    const user = await User.findOne({ email: email }); // Faltou `await` aqui.

    if (user) {
        await mongoose.disconnect(); // Faltou `await` aqui.
        throw new Error("Este e-mail já está em uso");
    }
    const nUser = new User({
        username,
        email,
        password: await bcrypt.hash(password, 10) // Faltou `await` aqui.
    });

    await nUser.save(); // Faltou `await` aqui.
};

I put comment in places where the await it was necessary.

  • 1

    It worked, thank you again, Luiz! =')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.