0

I have Node.js app, served by express, I got two different mongoose schema userModel and postMode, with my frontend being made with React.js. I'm creating a component that will create and display posts. Display post will contain username, avatar, date, text, and images. The problem is the avatar is in the userModel. Is there a way that I can also display the avatar from another schema? I'm thinking that I will compare the two schema based on if they have the same key value because both of them have username. To display the post I send Axios to get request based on the postModel.

Backend
export const getUserRelatedPost = asyncHandler(async (req, res) => {
  const postData = await postModel.find({});
  res.json(postData);
});

Schema postModel enter image description here

userModel

enter image description here

Thanks!

rjc30
  • 227
  • 4
  • 14
  • I'm not entirely sure I understand what you are asking, but in looking at the two schemas you shared, the values in the username element don't match. – Scott Gnile Mar 17 '21 at 13:28
  • I think the better way is to embedded user data in your post or create a ref (then populate) to UserModel. when you create new post That way you can limit number of request you made. – Vo Quoc Thang Mar 17 '21 at 13:29
  • @ScottGnile I apologize but it should be johndoe for both usernames. The output that I want is I want to get the avatar value from userModel by so i can use that on my post Component but the problem is the postModel is the one that i'm using on the post component. – rjc30 Mar 17 '21 at 13:42
  • @VoQuocThang Sir, can you give me some links on how to do that? Thanks! – rjc30 Mar 17 '21 at 13:43
  • 1
    @rjc30 here is the populate approach : https://stackoverflow.com/questions/38051977/what-does-populate-in-mongoose-mean – Vo Quoc Thang Mar 17 '21 at 13:55
  • Thank you so much @VoQuocThang – rjc30 Mar 17 '21 at 14:07

1 Answers1

1

You could use mongoose's populate feature

https://mongoosejs.com/docs/populate.html

In your postModel add a virtual 'user' element

const postSchema = Schema({
    //your existing postModel definition

});

postSchema.virtual('user', {
    ref: 'User',
    localField: 'username',
    foreignField: 'username',
    justOne: true
});

I am assuming your userModel exports User something like this:

const userSchema = Schema({
    //your existing userModel definition
})

const User = model('User', userSchema);

Then in you express route you ought to be able to do something like this:

export const getUserRelatedPost = asyncHandler(async (req, res) => {
    const postData = await postModel.find({})
        .populate({
            path: 'user',
            select: 'avatarPhoto'
        });
    //you should be able to access the avatar photo(s) like this
    console.log(postData.map(u => u.user.avatarPhoto)

    res.json(postData);
});
Scott Gnile
  • 482
  • 4
  • 7