Create an entry to a database using post request (mongoose, mongoDB, node express)
So in the last article, we learnt about how to set up a database schema:
const mongoose = require('mongoose')
// creates a table with name, email, password column
const userSchema = mongoose.schema({
name: String
email: String
password: String
})
// create a database model of userSchema, and call that model 'User'.
const User = mongoose.model('User', userSchema);
module.exports = { User }
and also about POST request in another article.
Assuming you have a code in index.js that imports User database model and connects to the mongo db:
const { User } = require('./models/User') // get User database model
//connect to mongoDB
const mongoose = require('mongoose')
mongoose.connect(someKey, {...})
We can do app.post() to register the behaviour of router at /register route.
A very basic structure would be this:
app.post('/register',(req,res)=>{
const user = new User(req.body)
user.save()
})
new User(req.body) creates an instance of schema, or a row that follows the database schema. Note that User is basically a class or 'model' that allows manipulation of schema (like creating an entry, updating it etc) easier. So user.save() is using a default method of that class to save the row made from request body to the mongodb database. But we want to also put a behaviour that if there's an error, the response of the request will have something in it that will notify the client about it.
(err, userInfo)=>{
if(err) return res.json({success: false, err})
return res.status(200).json({
success: true
})
}
is exactly what does this. All in all, the following will be the code that registers a row to the mongodb database, where the data of that row comes from the request body of someone's POST request to /register route.
app.post('/register',(req,res)=>{
const user = new User(req.body)
user.save((err, userInfo)=>{
if(err) return res.json({ success: false, err })
return res.status(200).json({
success: true
})
})
})