Search code examples
node.jsexpressnode-oracledb

How to display the result of the query?


I use this library oracle-sage. I have a request to create a user. The request itself is working. But there is such a problem that the displayed result looks like this:

{
    "isFulfilled": false,
    "isRejected": false
}

How can display the created entry in JSON format as a result?

module.exports.create = async function (req, res) {
    const candidate = await User.findOne(
        { LOGIN: req.body.LOGIN }
    )

    if (candidate) {
        res.status(409).json({
            message: 'This login is already taken. Try another one.'
        })
    } else {
        const salt = await bcrypt.genSaltSync(10)
        const password = await req.body.PASSWORD
        const user = User.create({
            LOGIN: req.body.LOGIN,
            EMAIL: req.body.PHONE,
            PASSWORD: bcrypt.hashSync(password, salt)
        });
        try {
            res.status(201).json(user)
        } catch (e) {
            console.log(e)
        }
    }
}

Solution

  • The problem is that Model.create returns a Promise object, not the user which is what you’re expecting. This is what the JSON that you’re seeing is—a promise object. You need to wait for that Promise to finish and then extract the return value. You can do this using the await keyword like you did in a few other lines. Which means that you should be calling:

    res.status(201).json(user)
    

    Edit: it doesn’t seem like getting the created value is part of the API docs and I can’t reproduce locally. You can store the value in a variable and return that.

    const userObj = {
        LOGIN: req.body.LOGIN,
        EMAIL: req.body.PHONE,
        PASSWORD: bcrypt.hashSync(password, salt)
    };
    const user = User.create(userObj);
    try {
        res.status(201).json(userObj)