Reputation: 609
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?
Upvotes: 0
Views: 1405
Reputation: 106
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.
Upvotes: 2