Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The code is written to upload a document to mongoDB with a photo attached.
The code works and the document is actually pushed to my mongoDB database.
However, I just want to return something once the function ends so that I can generate a proper response on my react front end.

So here's my problem:
<a href="https://i.stack.imgur.com/YbuIK.png">https://i.stack.imgur.com/YbuIK.png</a>[<a href="https://i.stack.imgur.com/YbuIK.png" target="_blank" title="New Window">^</a>]

Any idea where I went wrong here?

code base:
module.exports.createProduct = async (req, res, next) => {
	const files = req.files;
	let message;
	if(!files) {
		const error = new Error('Please choose files');
		error.httpStatusCode = 400;
		return next(error)
	}

	let imgArray = await files.map((file) => {
		let img = fs.readFileSync(file.path)
		return encode_image = img.toString('base64')
	})

	let result = await imgArray.forEach(async(src, index) => {
		
		let newProduct = new Product({
			productName: req.body.productName,
			description: req.body.description,
			price: req.body.price,
			stocks: req.body.stocks,
			addedBy: auth.decode(req.headers.authorization).email,
			filename: files[index].originalname,
			contentType: files[index].mimetype,
			imageBase64: src
		})
		
		let createNew = await newProduct.save().then(()=> {
			message = true;
			console.log(message)
			return message
		}).catch(error => {			
			if(error.name === 'MongoError' && error.code === 11000) {
				message = 'duplicate'
				console.log(message)
				return message
			} else {
				message = 'file not found'
				console.log(message)
				return message
			}
		})
		console.log(`From createNew: ${createNew}`)
		return createNew
	})	
	return result
}


What I have tried:

1.) returning the message variable at the end but it shows undefined on my postman.

2.) console.log(result) but it shows: [object Promise] on my terminal
Posted
Updated 5-Dec-21 23:06pm

Why are you mixing async/await with the old-style .then/.catch calls? Just use async code:
JavaScript
try {
    await newProduct.save();
    console.log(true);
    return true;
} catch (error) {
    if (error.name === 'MongoError' && error.code === 11000) {
        console.log('duplicate', error);
        return 'duplicate';
    }
    
    console.log('file not found', error);
    return 'file not found';
}
 
Share this answer
 
In addition to Richard's comment about correctly using async/await in your JS, you're also using it in places where it isn't fully supported. For example, the JS array functions forEach() and map() don't return Promise objects.

JavaScript
let imgArray = await files.map((file) => {
  let img = fs.readFileSync(file.path)
  return encode_image = img.toString('base64')
})

...

let result = await imgArray.forEach(async(src, index) => {

  ...

})

Should be:
JavaScript
let imgArray = files.map(file => {
  let img = fs.readFileSync(file.path)
  return img.toString('base64');
})

...

for (const [index, src] of imgArray.entries()) {

  ...
 
}

Array.prototype.forEach() - JavaScript | MDN[^] (documents that the return type is undefined)
Array.prototype.map() - JavaScript | MDN[^] (documents that the return type is an array)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900