const app = express(); const mongoose = require('mongoose') const dotenv = require('dotenv') const User = require('./models/userModel'); dotenv.config(); app.use(express.json()) mongoose.connect(process.env.URI) .then(() => { console.log("connected to mongoDB successfully...")
app.listen(process.env.PORT || 8000, (err) => { if(err) console.log(err); console.log("Running successfully at ", process.env.PORT) }) }).catch((err) => { console.log("error: ", [error in console][1]err) }) //Create API app.post("/", async(req, res) => { const [name, email,age] = await req.body try { const userData = await User.create({ name: name, email: email, age: age, }); res.status(201).json(userAdded) } catch (error) { res.status(400).json({error:error.message}) } }) app.get('/', function(req, res){ res.send("This is working. THIS IS / endpoint") })
It is not connecting with mongodb server.
You have 2 main issues with your code. Let's address the first one before you fix your TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
Firstly, in your code you have:
const [name, email,age] = await req.body
There is no need to use the the await
keyword here.
Using await pauses the execution of its surrounding async function until the promise is settled (that is, fulfilled or rejected). When execution resumes, the value of the await expression becomes that of the fulfilled promise.
Since you are not waiting for a promise to settle you can remove that await
keyword.
Secondly, you are using Destructuring assignment but you have used it in the context of req.body
being an array, but req.body
is an object. You need to use:
const {name, email, age} = req.body
To illustrate the difference. In a form submission req.body
may look like this:
{
//...
body:{
name: 'bob',
email: '[email protected]',
age: 60
}
//...
}
But because you have used const [name, email,age]
, the destructuring assignment syntax is expecting to see something like this:
{
//...
body:[
'bob',
'[email protected]',
60
]
//...
}
That's why you are getting the TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
. JavaScript Objects don't have a @@iterator method
. Arrays do.
Some built-in types have a default iteration behavior, while other types (such as Object) do not.