Home > Back-end >  Which way is a best to fetch data in node js from mongodb?
Which way is a best to fetch data in node js from mongodb?

Time:10-19

everyone I have such a question, I fetch data in node js from MongoDB, also I Have two routes where was fetched "users" and "posts", check the code:

// Mongoose schema models
const users = require('../models/users')
const posts = require('../models/posts')

routes.get('/users', (req, res) => {
   users.find({}, (err, users) => {
        res.end(users)
   })
})

routes.get('/posts', (req, res) => {
   posts.find({}, (err, posts) => {
        res.end(posts)
   })
})

What do you think? it is right? I know it works, but I want to know if it's good or if I can do better. also, consider that I get those data in react js and then I filter as I want and where I want. in addition, I want to get advice about redux, what do you think? it's necessary to use it when we get data? Share your opinion

thank's

CodePudding user response:

Reading from a DB is a async operation and you'll have to await the answer.

router.get('/users', async (req, res) => {   
  const users = await User.find().sort('name');   
  res.send(users); 
})

CodePudding user response:

This is pretty much it if you just want to fetch all the data and return it to the frontend.

However, I would suggest one addition to your query, and that is adding the .lean() to the query since it will increase the performance. By default, Mongoose will hydrate the data before returning it, so when you add .lean(), it will tell Mongoose that it should skip the hydration of the data and return the pure JavaScript objects.

Also, you should have error handling in case of an error.

// Mongoose schema models
const Users = require('../models/users')
const Posts = require('../models/posts')

routes.get('/users', async (req, res) => {
   try {
     const users = await Users.find().lean();
     return res.status(200).json(users);
   } catch (error) {
     return res.status(400).json({ success: false });
   }
})

routes.get('/posts', async (req, res) => {
   try {
     const posts = await Posts.find().lean();
     return res.status(200).json(posts);
   } catch (error) {
     return res.status(400).json({ success: false });
   }
})
  • Related