Home > OS >  How to make a GET request (MongoDB -- Express)?
How to make a GET request (MongoDB -- Express)?

Time:10-01

Here is POST request. But how to make a GET request?

const express = require('express');
const router = express.Router();
const signUpTemplateCopy = require('../models/SignUpModels')

router.post('/signup', (request, response) => {
    const signedUpUser = new signUpTemplateCopy({
        fullName: request.body.fullName,
        username: request.body.username,
        email: request.body.email,
        password: request.body.password
    })
    signedUpUser.save()
    .then(data => response.json(data))
    .catch(error => response.json(error))
})

module.exports = router;

Here is the database in MongoDB.

enter image description here

CodePudding user response:

I have included both probable codes for GET request. First one is for getting back all the users in your db and the second one is to get specific user by using the ObjectId which you have to pass as a parameter. Let me know if it works.

//Get all user
router.get('/getUsers', (request, response) => {
    signUpTemplateCopy.find()
    .then(data => response.json(data))
    .catch(error => response.json(error))
)};

//Get user by ObjectID
router.get('/getUserByID', (request, response) => {
    signUpTemplateCopy.findById(request.params.id)
    .then(data => response.json(data))
    .catch(error => response.json(error))
)};
  • Related