Pruteanu Alexandru
Pruteanu Alexandru

Reputation: 247

Find All Post By User ID

I use mongoose to populate "Post Schema" with information about users whic create the post.

postModule.js

const mongoose = require('mongoose');

 const postSchema = mongoose.Schema({
title:String,
description:String,
datePost:Date,
images:[String],
like:[String],
dislike:[String],
author:{
    type: mongoose.Schema.Types.ObjectId,
    ref:'User'
},
 });


postSchema.pre(/^find/,function(next){
this.populate({
    path:'author',
    select:'photo firstName lastName'
  });
next();
});


 const Post = mongoose.model('Post',postSchema);
 module.exports = Post;

This is the controller build in postController.js

//Get All User Post
exports.getUsersPost = catchAsync(async(req,res,nex)=>{
const userPost = await Post.find({author:req.params.userId});

res.status(200).json({
    status:"success",
    length:userPost.length,
    data:{
        post:userPost
    }
});
});

postRouter.js

router.route('/get-user-posts/:userId').get(authController.protect,postController.getUsersPost)

I don't know what is wrong, I recive in postman this error

Cannot GET /api/v1/get-user-posts/5f719092ba22b8373c72196
There is any option to resolve this problem and the result of request it must to by all the posts created by the user.

Upvotes: 0

Views: 856

Answers (1)

wiredmartian
wiredmartian

Reputation: 307

If your app.js looks like below, then you endpoint should be:

/api/v1/post/get-user-posts/5f719092ba22b8373c72196.

It takes the whole string in the use() function. So /api/v1/user/**Routes you've defined in your Routes files**

const sessionRoutes = require('./routes/sessionsRoutes'); 
    const userRoutes = require('./routes/userRoutes'); 
    const viewRoutes = require('./routes/viewRoutes'); 
    const postRoutes = require('./routes/postRoutes'); 
    
    app.use('/api/v1/session',sessionRoutes); 
    app.use('/api/v1/user',userRoutes); 
    app.use('/api/v1/post',postRoutes); 
    app.use('/',viewRoutes); 
    module.exports = app;

Also add and extra slash just to be sure app.use('/api/v1/user/', userRoutes)

Upvotes: 1

Related Questions