0

Hi i have the following code:

export function createProduct(req, res) {
    console.log("Execution")
    const product = new Product({ ...req.body })
    product.save(function (err, product) {
        if (err) {
            console.log("error")
            const errorResponse = {}
            for (let key in err.errors) {
                //ValidationError handler
                if (err.errors[key].properties) {
                    errorResponse[key] = err.errors[key].properties.message
                }
                //CastError handler
                else {
                    errorResponse[key] = err.errors[key].toString().split(":")[1]
                }
            }
            return res.status(400).send({ ...errorResponse })
        }
        console.log("created")
        return res.send({ product })
    })
}

There is no error on express side, console.log("Execution") is working and display this message correctly. I tested this by using Postman, when i send some data, response never come and on Postman there is error: "Error: socket hang up".

I've made console.log for req.body, and this is my output:

{
  name: 'Apple Iphone 11 Pro 64GB Space Gray',
  category: 'smartphone',
  price: 4699,
  inMagazine: { blocked: 0, inStock: 40 },
  shortDescription: 'Odkryj wszystkie zalety iPhone 11 Pro 512 GB Silver. Smartfona, który zawstydza podkręconą wydajnością. Posiada bowiem najszybszy w historii procesor A13 Bionic oraz baterię, która pozwala na wiele. Weź iPhone 11 Pro do ręki i rób zdjęcia, których nie powstydziłby się nawet profesjonalista. Teraz masz do tego odpowiednie narzędzie – nowy iPhone 11 Pro posiada potrójny aparat główny, działający w oparciu o uczenie maszynowe. Efekty swojej fotograficznej przygody wraz z najmniejszymi detalami możesz ocenić z kolei na olśniewającym ekranie Super Retina XDR.',
  images: [ { order: 1, src: '' } ]
}

Right after that, I found that I would check why it hangs, I had no error in the nodejs console. So I added two console.log to the code:

console.log("error")
console.log("created")

But both doesn't execute. So i made some code refactor and this works the same like above:

export async function createProduct(req, res) {
    try {
        const product = await Product.create({ ...req.body })
        console.log("created")
        return res.send({ product })
    } catch (err) {
        console.log("error")
        const errorResponse = {}
        for (let key in err.errors) {
            //ValidationError handler
            if (err.errors[key].properties) {
                errorResponse[key] = err.errors[key].properties.message
            }
            //CastError handler
            else {
                errorResponse[key] = err.errors[key].toString().split(":")[1]
            }
        }
        return res.status(400).send({ ...errorResponse })
    } 
}

I don't know what the cause of this problem could be. This is link to whole project: https://github.com/codemasternode/DietShopping

1
  • 1
    Show what does you passed in { ...req.body } please. Commented Jul 26, 2020 at 10:14

4 Answers 4

1

Assuming you know that if you are saving the products like this all the keywords in the req.body should be the same as in the Product schema. This should work:

exports.createProduct = async (req, res) => {
    try{
        const product = new Product(req.body).save();
        return res.json(product);
    }catch(err){
        const errorResponse = {}
            for (let key in err.errors) {
                if (err.errors[key].properties) {
                    errorResponse[key] = err.errors[key].properties.message
                }
                else {
                    errorResponse[key] = err.errors[key].toString().split(":")[1]
                }
            }
            return res.status(400).send({ ...errorResponse })
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try getting rid of the return(s) in front of the res. function calls

Like this:

export async function createProduct(req, res) {
try {
    const product = await Product.create({ ...req.body })
    console.log("created")
    res.send({ product })
} catch (err) {
    console.log("error")
    const errorResponse = {}
    for (let key in err.errors) {
        //ValidationError handler
        if (err.errors[key].properties) {
            errorResponse[key] = err.errors[key].properties.message
        }
        //CastError handler
        else {
            errorResponse[key] = err.errors[key].toString().split(":")[1]
        }
    }
    res.status(400).send({ ...errorResponse })
} 

1 Comment

This is link to whole repo: github.com/codemasternode/DietShopping
0

I've had an pre save in "products" model that doesn't let me go through. I was copying and pasting from other model and forget to remove unecesarry code.

Comments

0

I suggest you get rid of that callbacks and use clean async-await. By using this codes will be shorter too. And I think this will work. Try this.

export async function createProduct(req, res) {
    try{
        console.log("Execution")
        const product = new Product({...req.body})
        let result = await product.save()
        console.log("created",result)
        return res.send({ product })
    }catch(err){
        const errorResponse = {}
            for (let key in err.errors) {
                if (err.errors[key].properties) {
                    errorResponse[key] = err.errors[key].properties.message
                }
                else {
                    errorResponse[key] = err.errors[key].toString().split(":")[1]
                }
            }
            return res.status(400).send({ ...errorResponse })
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.