首页 > 解决方案 > 未获得登录用户的所有必需文档(帖子) - 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 }

标签: node.jsmongodbexpressmongodb-query

解决方案


试试下面的代码:

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')
        }
    })
}

推荐阅读