仅显示已登录用户的帖子

时间:2020-08-15 14:26:36

标签: node.js api express mongoose

我创建了一条路线来获取已登录用户的帖子,但是现在,当我为该路线调用api时,我正在获得所有用户的帖子。我应该在此处进行哪些更改,以便仅获得该登录用户的帖子,而不是数据库中所有用户的帖子?

route.js

router.get('/', auth, async (req, res) => {
    try {
      const posts = await Post.find().sort({ date: -1 });
      res.json(posts);
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  });

帖子的模型架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const PostSchema = new Schema ({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    title:{
        type: String,
        required: true
    },
    text: {
        type: String,
        required: true
    },
    name: {
        type: String
    },
    
    email: {
            type: String
    }
    ,
    age: [{
        type: String,
        required: true
       
    }],
    date: {
        type: Date,
        default: Date.now
    }
    
})

module.exports = Post = mongoose.model('post', PostSchema)

1 个答案:

答案 0 :(得分:1)

您需要将filter参数传递给find方法。

假设您的auth中间件将经过身份验证的用户添加到req对象,则route.js的第3行应为:

      const posts = await Post.find({ user: req.user._id }).sort({ date: -1 });