0

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.

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.