Sorting A-Z/Date data from router.get? - node.js

Quick question: how can I sort my posts data by date?
router.get('/', async (req, res) => {
try {
const posts = await Post.find()
res.json(posts)
}
catch (err) {
res.json({message: err})
}
})
I came from Django and there you could do something like:
posts = Post.objects.filter().order_by('date')
I'm fairly new to NodeJS and Express. Thanks a lot!

It depends on the what the data structure of the date property is. If they are in JS timestamp format:-
router.get('/', async (req, res) => {
try {
const posts = await Post.find();
const sortedPosts = posts.sort((a,b) => {
return new Date(b.date) - new Date(a.date);
});
res.json(sortedPosts)
}
catch (err) {
res.json({message: err})
}
})
Here I've used the array's sort() method. Learn more

Related

Which way is a best to fetch data in node js from mongodb?

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
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);
})
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 });
}
})

findById not working in mognodb with nodejs

This is my code;
I'm try for update user data. like so you are seen this code. But result coming null.
I'm not understand. please help me guys
// #Router UPDATE /updateforslip/:id
// #desc UPDATE update by ID
// #access Private
router.put('/update/user/data/:id', async (req, res) => {
var update = Pan.findByIdAndUpdate(req.params.id, {
$set: req.body
})
console.log(update)
update.exec((error, data) => {
if (error) throw error;
res.json(data)
})
})
Coming result
in console.log(update)
null
I'm using postman for request.
try this:
router.put('/update/user/data/:id', async (req, res) => {
tyr{
var update = await Pan.findByIdAndUpdate(req.params.id, {$set: req.body})
res.json(update)
}catch (err){
throw error;
}
Just try like this, don’t use exec() when you want to uae async await
and use try/carch for handling errors
try{
var data = await Pan.findByIdAndUpdate(req.params.id, {
$set: req.body
}).lean();
res.json(data)
},
catch(error){
}

Query data in EJS with NodeJS and Mongoose

I've captured data and display them by doing this:
const items = [];
Task.find({},(err,tasks)=>{
if(err){
console.log(err);
}else{
tasks.forEach((task)=>{
items.push(task.name);
})
}
})
app.get("/", (req, res) => {
today = date.getDate();
res.render('list', { kindOfDay: today, items: items });
})
But when I try to do this instead, it failed to display the data with out any error:
app.get("/", (req, res) => {
const items = [];
Task.find({}, (err, tasks) => {
if (err) {
console.log(err);
} else {
tasks.forEach((task) => {
items.push(task.name);
//console.log(task.name) still works
})
}
});
today = date.getDate();
res.render('list', { kindOfDay: today, items: items });
})
Does anybody knows why the code above refuse to display data when I render the 'list' page?
Thank you!
mongoose find method is asynchronous, res.render might/would execute before the array gets populated. your code should be as below
app.get("/", (req, res) => {
const items = [];
Task.find({}, (err, tasks) => {
if (err) {
console.log(err);
} else {
tasks.forEach((task) => {
items.push(task.name);
//console.log(task.name) still works
});
}
today = date.getDate();
res.render('list', { kindOfDay: today, items: items });
});
})

mongoose not returning posts when *.find() is wrapped in a function

i have setup a simple express rest api and i want to get all posts when a certain route is requested from my rest server ("/api/posts")
i tried to console.log(posts) and it shows me the posts but when i try to go to the route http://localhost:5000/api/posts it shows me a blank page although console.logging the posts shows me the posts why is this
function getAllPosts() {
Post.find((err, posts) => {
if (err) {
console.error(err);
}
console.log(posts);
console.log("all posts requested");
return posts;
});
}
router
.route("/")
.get((req, res) => {
let posts = getAllPosts();
res.send(posts);
})
i expected to get the posts json when i go to http://localhost:5000/api/posts
when you are returning value from the getAllpost functions, routes are getting undefined value because of async. Try to edit your code like this:
function getAllPosts(req, res) {
Post.find((err, posts) => {
if (err) {
console.error(err);
}
console.log(posts);
console.log("all posts requested");
res.send( { data: posts} );
});
}
router
.route("/").get((req, res) => {
getAllPosts(req, res);
});
This has to do with the asynchronous nature of the code you have here. res.send is executing before Post.find() can resolve. You only want to res.send(posts) once the database query has finished fetching the data, if using callbacks, as you are in your example, you would do this inside of the callback. You could do something like this.
router
.route("/")
.get((req, res) => {
Post.find({}, (err, posts) => {
if (err) {
return res.status(500).send(err)
}
res.send(posts)
})
})

ExpressJS Mongoose render view after getting data from database

I need to render view after mongodb provide data from database. I write this code but the main problem is view is generated before getting data.
router.get('/', async(req, res, next)=> {
try{
const products = await Product.find({});
res.render('shop/index', { title: 'Express',products });
}catch(e){
console.log(e);
}
});
You could try doing something like this:
router.get("/", async (req, res, next) => {
Product.find({}, (err, items) => {
if (err) {
console.log(err);
res.status(500).send("An error occurred", err);
} else {
res.render("home", { items });
}
});
});
Actually everything looks great, idk why it's not working. I probably write something like this:
router.get("/", async (req, res) => {
const products = await Product.find({});
if (!products) return res.render("error");
res.render("shop/index", {
title: "Express",
products
});
});

Resources