我创建了一条路线来获取已登录用户的帖子,但是现在,当我为该路线调用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)
答案 0 :(得分:1)
您需要将filter
参数传递给find
方法。
假设您的auth
中间件将经过身份验证的用户添加到req
对象,则route.js
的第3行应为:
const posts = await Post.find({ user: req.user._id }).sort({ date: -1 });