0

I am trying to add a product document to the MongoDB by using mongoose v5.6.3 in NodeJS, but in callback function, it cannot assign result to the returning value.

Here is my function:

public async addProduct(productInfo: Product) {
        let result = null;

        let newProduct = new ProductModel(productInfo);
        newProduct.uuid = id();

        await newProduct.save(async (err,product) => {
            if(err){
                throw new ProductCreateError();
            }
            result = product;
        });
        return result;
    }

Note that, Product and ProductModel are different but same in terms of parameters. Product is an interface and ProductModel is a mongoose model.

When this function is called, it returns the initial value of 'result'

Problem might occur because of async/await but im not sure. How can I fix this?

1 Answer 1

2

Since save() is a asynchronous task it will always return null.The function will return null before returning product.

modify the code as

public async addProduct(productInfo: Product) {
let result = null;
  try {
    let newProduct = new ProductModel(productInfo);
    newProduct.uuid = id();
    result = await newProduct.save();
  } catch (e) {
    throw new ProductCreateError();
  }
}

Try this code and let me know.

Sign up to request clarification or add additional context in comments.

1 Comment

Dude sorry for the late answer and this works fine! Thank you a lot

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.