Reputation: 126
I am trying to show user names in posts who posted this on this website. I am successful in find users and also passing data to ejs temple and also getting user data by using ejs tag <%= user%>
but when I call <%=user.name%>
it say undefined also try to call like .username
and email
it's also undefined.
Here is ejs code
<p>Contributed by <span><%=user.name%></span> <span><%=post.date%></span></p>
<%= console.log(user.username)%> // user.name and user.email is undefined
<%= console.log(user)%>// user is working and show all data which is store in MongoDB
Here is MongoDB schema for the user
const userSchema = new mongoose.Schema({
name: String ,
email:String,
password:String,
profile:{data: Buffer,contentType: String}
}
app.js route for finding data and render to posts page
app.get("/posts/:id", async (req,res) => {
const id = req.params.id;
const post = await Post.findOne({ _id: id });
const comments = await Comment.find({ post: id });
const user = await User.find({_id: post.user});/// I have store user id into post schema
console.log(user)// getting user data
console.log(post.user)// getting user id from post
res.render('posts', {
post: post,
comments: comments,
user: user
});// successfully render data to ejs
});
Upvotes: 0
Views: 279
Reputation: 126
i have solved it by using User.findById({})
instead of User.find({})
const user = await User.findById({_id: post.user});
Upvotes: 1