How can i display newest user post in my app? i have a backend route which display user post but i want that route display latest post of user So how can i do that in my code?
My code:
router.get('/postdata', async (req, res) => {
try {
// Find all users in the database
const users = await User.find();
// Map over the users array and return an array of objects
// with the same username, profile_image, and postImage
const userData = users.flatMap(user => {
return user.posts.map(post => ({
username: user.username,
profile_image: user.profilepic,
postImage: post.post,
}));
});
return res.json(userData);
} catch (err) {
return res.status(500).json({ error: err.message });
}
});
If your posts model has created_at or updated_at properties that keep track of when an image was uploaded, you could use that to sort the array in your map.
Let's say your userData array has similar output to this.
[
{
username: 'user1',
profile_image: 'https://your_domain.com/user1-profile.jpg',
postImage: 'https://your_domain.com/user1-post1.jpg',
created_at: '2023-01-01T11:00:00.000
},
{
username: 'user2',
profile_image: 'https://your_domain.com/user2-profile.jpg',
postImage: 'https://your_domain.com/user2-post1.jpg',
created_at: '2023-01-01T12:00:00.000
}
]
Then you can sort the array before rendering it.
const sorteduserData = userData.sort((a, b) => {
return new Date(b.created_at) - new Date(a.created_at);
});
It's a good practice to have your backend do the sort to reduce overhead on the front-end and to have your application load faster.
Many of headless CMSs have these features built in.
Related
I have read all sorts of variations of this on stackoverflow but I cannot seem to find a post that exactly explains what I'm trying to achieve, at the same time I believe this has to be a very common task during saving data.
So I need to save data to one collection and then read the _id from that doc and save it to a doc in a different collection. I have the following code and I can see the correct data with console.log but I don't see the data being saved to the database.
Appreciate if someone can guide me in the right direction.
Thank you!
router.post('/signup', async (req, res) => {
const { email, password, name, country } = req.body;
try {
const user = new User({ email, password });
await user.save((error, doc) => {
if (error) {
console.log(error);
} else {
const userProfile = new UserProfile({ userId: doc._id, name, country });
userProfile.save((error, doc) => {
if (error) {
console.log(error)
} else {
console.log(doc) // Can see this log with the correct data
}
});
}
});
const token = jwt.sign({userId: user._id}, 'MY_KEY');
res.send({ token });
} catch(error) {
return res.status(422).send(error.message)
}
})
Hi i'm trying to add an update function for my SPA and seem to be running into this issue
blogsRouter.put('/:id', (request, response) => {
const body = request.body
const blog = Blog ({
title: body.title,
author: body.author,
url: body.url,
likes: body.likes,
userId: body.userId,
userName: body.userName
})
Blog.findByIdAndUpdate(request.params.id, blog)
.then(updatedBlog => {
response.json(updatedBlog.toJSON())
})
.catch(error => console.log(error))
})
it catches this error
Performing an update on the path '_id' would modify the immutable field '_id'
I'm not sure what is happening here since to my understanding i'm not trying to update the _field and if my approach is trying to do it automatically what would be a better way to do this?
Because you are passing a full Mongoose model as update.
You are using const blog = Blog({ ... }), this creates a full Mongoose model with an automatic _id.
This object is passed as an update. Since it has its own _id, the update is rejected because _id is an immutable field.
Solution : pass a simple object as update, not a full Mongoose model.
blogsRouter.put('/:id', (request, response) => {
const body = request.body
const blog = { // <-- Here
title: body.title,
author: body.author,
url: body.url,
likes: body.likes,
userId: body.userId,
userName: body.userName
}
Blog.findByIdAndUpdate(request.params.id, blog)
.then(updatedBlog => {
response.json(updatedBlog.toJSON())
})
.catch(error => console.log(error))
})
I want to get updated table values after I add user to my "WOD" table. For instance, I have 2 users in my WOD table and after I add third user , I want to return a response to client with I have just inserted data (third guy). But now , I can only return first 2 users because I can not take updated values. Of course I can make another query to get updated table values after I insert, but is there any better solution ? Here is my codes;
const addUser = async (req, res) => {
try {
const { userId, wodId } = req.body;
if (!userId || !wodId) {
res.status(400).send({ status: false, message: 'need userId and wodId' });
}
const wod = await Wod.findByPk(wodId, {
include: [
{
model: User,
as: 'Participants',
through: { attributes: [] }
}
]
});
//check capacity if full.
if (wod.Participants.length >= wod.capacity) {
res
.status(403)
.send({ status: false, message: 'Capacity of this class is full!' });
}
const result = await wod.addParticipants(userId);
res.status(201).json({ status: !!result, wod });
} catch (error) {
res.status(500).send({ status: result, message: error.message });
console.log(error.message);
}
};
As a result of many-to-many association sequelize.sync will generate some functions for us. You are used addParticipants function and this returns an array that added to the assocation(userwod) table.
In this array you will find some id fields(join table fields) because you just run like this INSERT INTO 'user_wods' ('user_id''wod_id') VALUES (2,1). If you want to return the added user's information then you should run a SELECT * FROM 'user' WHERE 'id'=2.
You must call reload function for fetch the third guy.
await wod.reload()
I'm trying to create a data entry on the firebase database to store additional information about a user when they register on my site.
I've tried to write data to the database in the .then() function following createUserWithEmailAndPassword() as that's the only way for me to extract the user id for the user (I'm hoping to use the uid as the key field of the record I create)
(req, res) => {
// extract user data from the form
const newUser = {
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
pw: req.body.pw,
pw_c: req.body.pw_c
}
// carry out validation
const { valid, errors } = validateRegistrationData(newUser);
if (!valid) return res.status(400).json(errors);
// create new firebase user
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.pw)
.then(data => {
let uid = data.user.uid;
// make a database entry to store the users info
// by default, assumes that the user is a secondary user
let userData = {
fname: newUser.fname,
lname: newUser.lname,
email: newUser.email,
utype: 1,
createdon: admin.firestore.FieldValue.serverTimestamp(),
intitems: []
}
newUserDoc = db
.collection("users")
.doc(uid)
.set(userData)
return res.status(200).json("Success: new user created.");
})
.catch(err => {
if (err.code === "auth/email-already-in-use"){
return res.status(400).json({ email: "Email is already in use" });
} else {
return res.status(500).json({ error: err.code });
}
});
return res.status(200).json("Success: new user created.");
}
The server responds with {Success: new user created."}. The authentication part seems to work as a new user is created in the Authentication section of my firebase console. However, no new data entries appear in the users collection of my database.
.set returns a promise that still needs to run to completion. However, currently you're not waiting on the promise, and instead just responding via res.send.
You can append .then(() => { do stuff here }) to the end of .set. If it's the last thing you're doing in that function, you can just do res.send from there.
return db.collection("users").doc(uid).set(userData).then(() => {
return res.status(200).json("Success: new user created.");
})
.catch(error => {
console.log(error)
})
I'm newbie with nodejs. What I want to do is load users data, insert it to array and then assign it to variable.
If in PHP, I need to load data using my model.
I already have one method in nodejs to retrieve all users data (I already create the API).
This is my API routes :
router.get('/', ctl.getAllUser);
ctl.getAllUser refers to this method :
getAllUser(req, res, next) {
db.any('SELECT * FROM users')
.then((data) => {
if (data.length === 0) {
throw abort(404, 'No user data yet', 'Empty user table');
}
return res.status(200).json({
status: 'success',
data,
message: 'Retrieved all users data',
});
})
.catch(err => next(err));
},
usually I access it using :
http://localhost:5000/api/v1/users
But I don't know how to load it, and assign it to one variable.
This is the format that I want.
var users = [{
id: 1,
name: "indra.gunawan",
email: "indra.gunawan#gmail.com",
password: "123456"
}, {
id: 2,
name: "Jamie Christian",
email: "j.christianm#gmail.com",
password: "123456"
}];
module.exports = users;
Since your getAllUser() function returns a promise you need to subscribe it.
Something like this:
ctl.getAllUser().subscribe(data => console.log(data));