You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
to create a new entry in the database, call the .save() method on the object. This usually goes in a route for the POST method
constData=require('../models/data');constdata=awaitnewData({
name
}).save()
/routes/ folder
this will store the routes for the REST api. create a route for each type of data stored in the database.
constexpress=require('express');constbodyParser=require('body-parser');constmongoose=require('mongoose');constdataRoute=require('./routes/data');constrouter=require('express').express.Router();constData=require('../models/data');//mongoDBmongoose.Promise=global.Promise;mongoose.connect(getSecret(secretNames.dbUri)).then(()=>{console.log('Connected to mongoDB');},(err)=>console.log('Error connect ing to mongoDB',err));router.post('/',async(req,res)=>{try{const{name}=req.body;constdata=awaitnewData({name}).save()res.status(201).json({title: 'Created New Data',detail: 'Successfully create new dataentry',json: { name,}});}catch(err){res.status(400).json({errors: [{title: 'RegistrationError',detail: 'Something wentwrong',errorMessage: err.message,},],});}});
server.js file
this is where the server goes and singleton objects. include each route and
//express constapp=express();constport=getSecret(secretNames.port);//middlewareapp.use(bodyParser.json());app.use(cors())//routesapp.use('/api/data',dataRoute);app.listen(port,()=>{console.log(`Server running on port ${port}`);});module.exports={ app };