Home > Enterprise >  How to get all users from MongoDB?
How to get all users from MongoDB?

Time:12-09

I'm trying to get all my users from MongoDB, I've readed all documentations, but nothing helps.. What I'm trying to do is set my back-end mainController and create a get request which helps me get all users in front, so I can display them in my page. I'm still learning how to work with MongoDB, so sorry for my awful question.

mainController:

const uid = require('uid-safe')
const bcrypt = require('bcrypt')
const UserSchema = require('../schemas/UserSchema');
const { db } = require('../schemas/UserSchema');
const { default: mongoose } = require('mongoose');

module.exports = {
    register: async (req, res) => {
        const { username, email, password, image, city, country, firstName, lastName, phone, gender, birth } = req.body;
        const userExists = await UserSchema.findOne({ username });
        if (userExists) {
            return res.send({ error: true, message: 'User with this username exists', data: null });
        }
        const emailExists = await UserSchema.findOne({ email });
        if (emailExists) {
            return res.send({ error: true, message: 'User with this email exists', data: null });
        }
        const id = await uid(7);
        const hashedPass = await bcrypt.hash(password, 3);
        const user = new UserSchema({
            secret: id,
            username,
            email,
            password: hashedPass,
            image,
            city,
            country,
            firstName,
            lastName,
            phone,
            gender,
            birth
        });
        await user.save();
        return res.send({ error: false, message: 'User successfully registrated!', data: null });
    },
    login: async (req, res) => {
        const { username, password } = req.body;
        const loginUser = await UserSchema.findOne({ username });
        if (loginUser) {
            const passMatch = bcrypt.compare(password, loginUser.password)
            if (passMatch) {
                return res.send({ error: false, message: `Welcome back ${username}!`, data: loginUser })
            }
            return res.send({ error: true, message: 'Invalid password', data: null });
        };
        return res.send({ error: true, message: 'Invalid username', data: null });
    },
    getSingleUser: async (req, res) => {
        const { secret } = req.params;
        const findUser = await UserSchema.findOne({ secret });
        if (findUser) {
            return res.send({ error: false, message: 'User found', data: findUser });
        }
        return res.send({ error: true, message: 'User not found', data: null });
    },
    updateUser: async (req, res) => {
        try {
            const updateduser = await User.updateOne({ secret: req.params.secret }, { $set: req.body });
            res.status(200).json(updateduser);
        } catch (error) {
            res.status(400).json({ message: error.message });
        }
    }
};  

mainRouter:

 const express = require('express')

const { login, register, getSingleUser, authSession, usersApi } = require("../controller/mainController")
const { loginValidate, registerValidate } = require("../middleware/authValidator")

const mainRouter = express.Router()

mainRouter.post('/register', registerValidate, register);

mainRouter.post('/login', loginValidate, login);

mainRouter.get('/user/:secret', getSingleUser)

module.exports = mainRouter;

Thank you!

CodePudding user response:

I think you can use the find function.

const uid = require('uid-safe')
const bcrypt = require('bcrypt')
const UserSchema = require('../schemas/UserSchema');
const { db } = require('../schemas/UserSchema');
const { default: mongoose } = require('mongoose');

module.exports = {
    register: async (req, res) => {
        const { username, email, password, image, city, country, firstName, lastName, phone, gender, birth } = req.body;
        const userExists = await UserSchema.findOne({ username });
        if (userExists) {
            return res.send({ error: true, message: 'User with this username exists', data: null });
        }
        const emailExists = await UserSchema.findOne({ email });
        if (emailExists) {
            return res.send({ error: true, message: 'User with this email exists', data: null });
        }
        const id = await uid(7);
        const hashedPass = await bcrypt.hash(password, 3);
        const user = new UserSchema({
            secret: id,
            username,
            email,
            password: hashedPass,
            image,
            city,
            country,
            firstName,
            lastName,
            phone,
            gender,
            birth
        });
        await user.save();
        return res.send({ error: false, message: 'User successfully registrated!', data: null });
    },
    login: async (req, res) => {
        const { username, password } = req.body;
        const loginUser = await UserSchema.findOne({ username });
        if (loginUser) {
            const passMatch = bcrypt.compare(password, loginUser.password)
            if (passMatch) {
                return res.send({ error: false, message: `Welcome back ${username}!`, data: loginUser })
            }
            return res.send({ error: true, message: 'Invalid password', data: null });
        };
        return res.send({ error: true, message: 'Invalid username', data: null });
    },
    getSingleUser: async (req, res) => {
        const { secret } = req.params;
        const findUser = await UserSchema.findOne({ secret });
        if (findUser) {
            return res.send({ error: false, message: 'User found', data: findUser });
        }
        return res.send({ error: true, message: 'User not found', data: null });
    },
    updateUser: async (req, res) => {
        try {
            const updateduser = await User.updateOne({ secret: req.params.secret }, { $set: req.body });
            res.status(200).json(updateduser);
        } catch (error) {
            res.status(400).json({ message: error.message });
        }
    },
    getAllUsers: async(req, res) => {
        try {
            const allUser = await User.find({});
            res.status(200).json(allUser);
        } catch (error) {
            res.status(400).json({ message: error.message });
        }
    }
};  

 const express = require('express')

const { login, register, getSingleUser, authSession, usersApi, getAllUsers } = require("../controller/mainController")
const { loginValidate, registerValidate } = require("../middleware/authValidator")

const mainRouter = express.Router()

mainRouter.post('/register', registerValidate, register);

mainRouter.post('/login', loginValidate, login);

mainRouter.get('/user/all', getAllUsers);

mainRouter.get('/user/:secret', getSingleUser);

module.exports = mainRouter;

  • Related