I am new to both Mongo and Stackoverflow, and I have a question so basic that I can’t find it anywhere online.
I am trying to query a Mongo database with the following code in an index.js file:
app.post('/users', async (req, res) => {
await Users.findOne({ Username: req.body.Username })
.then((user) => {
if (user) {
return res.status(400).send(req.body.Username + 'already exists');
} else {
Users
.create({
Username: req.body.Username,
Password: req.body.Password,
Email: req.body.Email,
Birthday: req.body.Birthday
})
.then((user) => {res.status(201).json(user) })
.catch((error) => {
console.error(error);
res.status(500).send('Error' + error);
})
}
})
.catch((error) => {
console.error(error);
res.status(500).send('Error' + error);
});
});
This should allow me to create a new “user” based on the following schema in a models.js file:
let userSchema = mongoose.Schema({
Username: {type: String, required: true},
Password: {type: String, required: true},
Email: {type: String, required: true},
Birthday: Date,
FavoriteMovies: [{type: mongoose.Schema.Types.ObjectId, ref: 'Movies'}]
});
However, attempting to query this in Postman crashes my server and displays the following error (that the Username part of req.body.Username is undefined):
Terminal Error
Any time I try to use req.body.Username, it crashes and says that Username is undefined. However, all users in the Users model have Usernames; also, using req.params.Username functions as normal. I have been running into this problem for days now and can’t seem to solve it.