Reputation: 1
I am trying to solve the promblem where const userPosts = await Post.find({user : req.user.id }) will only returns an empty array in the following code.
getPost : async (req, res) => {
try {
const userPosts = await Post.find({user : req.user.id})
res.render('profile.ejs',{posts : userPosts, user : req.user})
// console.log(req.user.id)
console.log(userPosts)
}catch(err){
console.error(err)
}
},
I am using a post schema which is taking a ref to my other schema User like so ie
const PostSchema = new mongoose.Schema({ title : { type: String, required : true, }, caption : { type: String, required : true, }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', }, })
const UserSchema = new mongoose.Schema( { username : { type : String, unique : true, }, email : { type : String, unique : true, }, password : { type : String, } })
The ultimate goal is to query the Post collection of all posts created by the logged in user, when logging req.user.id i get the correct id that is present in the User database, but there seems to be a disconnect with the referencing. I would greatly appreciate any help, thankyou.
The ultimate goal is to query the Post collection of all posts created by the logged in user, when logging req.user.id i get the correct id that is present in the User database, but there seems to be a disconnect with the referencing where only an emoty array is returned when i know there are documents created that match the user id. I would greatly appreciate any help, thankyou.
Upvotes: 0
Views: 42
Reputation: 11
req.query.id is a string,to fix it you can use
await Post.find({user : new mongoose.Types.ObjectId(req.user.id)}),
ObjectId as String is supported by findById, where Id should be primary key.
Upvotes: 0