node.js - 未获得登录用户的所有必需文档(帖子) - MongoDB/Node.js
问题描述
我想获取登录用户的帖子并显示在他的提要上。相反,现在,我正在获取所有用户的所有帖子。我只想显示用户的帖子。
用户.js
const userSchema = new Schema({
username: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Post"
}]
}, { timestamps: true })
Post.js
const postSchema = new Schema({
postTitle: { type: String, required: true },
postDescription: { type: String, required: true },
user: { type: Schema.Types.ObjectId, ref: "User" },
}, { timestamps: true }
)
router.get("/posts/:id", usersController.getUserPosts)
usersController.js
getUserPosts: (req, res) => {
User.findById(req.params.id).populate("posts").exec((err, posts) => {
if (err) console.log(err)
console.log(posts)
})
}
我得到这个:
{ posts: [],
_id: 5e4e3e7eecd9a53c185117d4,
username: 'rick',
email: 'rick@gmail.com',
createdAt: 2020-02-20T08:08:30.878Z,
updatedAt: 2020-02-20T08:08:30.878Z,
__v: 0 }
解决方案
试试下面的代码:
const mongoose = require('mongoose');
const id = mongoose.Types.ObjectId(req.user.userId);
/** Assuming 'req.user._id' is a string & converting it into ObjectId() to match with user field, Also updated find syntax */
getUserPosts: (req, res) => {
Post.find({ user: id }, (error, posts) => {
if (error) console.log("error occurred"); /** return from here */
if (posts.length) {
console.log(
"currentUser->", req.user,
"posts by this user->", posts
)
} else {
console.log('No posts found for given user')
}
})
}
推荐阅读
- node.js - Discord.js - Delete messages without image
- python - AttributeError: __enter__: requests.get Python
- javascript - React:重复调用组件 setState
- reactjs - 如何获取 API?
- highcharts - Highcharts 在旧版本中查看全屏
- android - 未解决的参考:android
- crystal-lang - 在 Crystal 中使用 splats 参数调用方法
- c++ - 试图让我的第一个程序循环(c++)
- smtp - 使用 mailx 发送内联 html (Heirloom mailx 12.4)
- crystal-lang - 有什么方法可以在 Crystal 中启用 Float 和 Int 吗?