使用猫鼬填充时返回一个空的帖子数组

Posted

技术标签:

【中文标题】使用猫鼬填充时返回一个空的帖子数组【英文标题】:Returning an empty array of posts when using mongoose populate 【发布时间】:2020-06-21 16:43:12 【问题描述】:

我正在尝试获取特定用户的帖子。它返回给我一个空的帖子数组。这是我的代码。我想我已经正确地引用了所有内容,一定有什么错误。

User model

const Schema = mongoose.Schema

const userSchema = new Schema(
    username:  type: String, required: true ,
    email:  type: String, reuired: true ,
    password:  type: String, required: true ,
    posts:[ type: Schema.Types.ObjectId, ref: "Post" ]
,  timestamps: true )

Post model

const Schema = mongoose.Schema;

const postSchema = new Schema(
  title:  type: String, required: true ,
  content:  type: String, required: true ,
  user:  type: Schema.Types.ObjectId, ref: "User" ,
,  timestamps: true 

router.get("/posts/:id", usersController.getUserPosts)

    getUserPosts: (req, res) => 
        User.findById(req.params.id, async (err, user) => 
            if (err) 
                return res.status(500).json( error: "Server error" )
             else if (!user) 
                return res.status(400).json( error: "No user" )
             else if (user) 
                user = await User.populate("user", 
                  path: "posts",
                  model: "Post"
              )
            return res.status(200).json( user )
         
      )
    

编辑

数据库中的用户是:

/users/list


    "users": [
        
            "posts": [],
            "_id": "5e66496fcaf5d6697ca3fdbc",
            "username": "JimmyPage",
            "email": "jimmypage@gmail.com",
            "password": "$2b$10$mu0IcHADj5YVIT/66EEfPOxL3cvEjqDsnJUcrST8ZcatTOcQ42kn6",
            "createdAt": "2020-03-09T13:49:35.834Z",
            "updatedAt": "2020-03-09T13:49:35.834Z",
            "__v": 0
        ,
        
            "posts": [],
            "_id": "5e66499fcaf5d6697ca3fdbe",
            "username": "AxlRose",
            "email": "axlrose@gmail.com",
            "password": "$2b$10$H3X3efz02RonlvNXaRPr2eEbflSiFK1ITFdbyT2igUGDK9gDpIJqO",
            "createdAt": "2020-03-09T13:50:23.702Z",
            "updatedAt": "2020-03-09T13:50:23.702Z",
            "__v": 0
        
    ]

帖子如下所示:

/posts/list


    "posts": [
        
            "_id": "5e66498ccaf5d6697ca3fdbd",
            "title": "Jimmy Page's post",
            "description": "This is Jimmy Page's post",
            "user": 
                "posts": [],
                "_id": "5e66496fcaf5d6697ca3fdbc",
                "username": "JimmyPage",
                "email": "jimmypage@gmail.com",
                "password": "$2b$10$mu0IcHADj5YVIT/66EEfPOxL3cvEjqDsnJUcrST8ZcatTOcQ42kn6",
                "createdAt": "2020-03-09T13:49:35.834Z",
                "updatedAt": "2020-03-09T13:49:35.834Z",
                "__v": 0
            ,
            "createdAt": "2020-03-09T13:50:04.840Z",
            "updatedAt": "2020-03-09T13:50:04.840Z",
            "__v": 0
        ,
        
            "_id": "5e6649b5caf5d6697ca3fdbf",
            "title": "Axl Rose's Post",
            "description": "This is Axl Rose's Post",
            "user": 
                "posts": [],
                "_id": "5e66499fcaf5d6697ca3fdbe",
                "username": "AxlRose",
                "email": "axlrose@gmail.com",
                "password": "$2b$10$H3X3efz02RonlvNXaRPr2eEbflSiFK1ITFdbyT2igUGDK9gDpIJqO",
                "createdAt": "2020-03-09T13:50:23.702Z",
                "updatedAt": "2020-03-09T13:50:23.702Z",
                "__v": 0
            ,
            "createdAt": "2020-03-09T13:50:45.751Z",
            "updatedAt": "2020-03-09T13:50:45.751Z",
            "__v": 0
        ,
        
            "_id": "5e664b7bf120ab6c0d9999c9",
            "title": "Jimmy Page's second post",
            "description": "This is Jimmy Page's second post\n\n",
            "user": 
                "posts": [],
                "_id": "5e66496fcaf5d6697ca3fdbc",
                "username": "JimmyPage",
                "email": "jimmypage@gmail.com",
                "password": "$2b$10$mu0IcHADj5YVIT/66EEfPOxL3cvEjqDsnJUcrST8ZcatTOcQ42kn6",
                "createdAt": "2020-03-09T13:49:35.834Z",
                "updatedAt": "2020-03-09T13:49:35.834Z",
                "__v": 0
            ,
            "createdAt": "2020-03-09T13:58:19.261Z",
            "updatedAt": "2020-03-09T13:58:19.261Z",
            "__v": 0
        
    ]

我在我的问题中添加了上述代码。我一直被困在这种状态,就像我试图在他的个人资料中显示用户的帖子一样,并且还计划显示所有用户帖子的全球供稿。

如果你能帮助我,那就太好了。我会很感激的。谢谢。

列表帖子控制器是这样的:

listposts:  (req, res) => 
    Post.find(, async (error, posts) => 
        if (error) 
            return res.status(500).json( error: "something went wrong" )
         else if (!posts) 
            return res.status(400).json( msg: "sorry no posts" )
         else if (posts) 
            posts = await Post.populate(posts, 
              path: 'user',
              model: 'User'
            );
            return res.status(200).json( posts )
        
    )

用户文档:


     "_id" : ObjectId("5e66496fcaf5d6697ca3fdbc"),
      "posts" : [ ],
      "username" : "JimmyPage",
      "email" : "jimmypage@gmail.com",
      "password" : "$2b$10$mu0IcHADj5YVIT/66EEfPOxL3cvEjqDsnJUcrST8ZcatTOcQ42kn6",
      "createdAt" : ISODate("2020-03-09T13:49:35.834Z"),
      "updatedAt" : ISODate("2020-03-09T13:49:35.834Z"), "__v" : 0 


 
    "_id" : ObjectId("5e66499fcaf5d6697ca3fdbe"),
     "posts" : [ ],
     "username" : "AxlRose",
     "email" : "axlrose@gmail.com",
     "password" : "$2b$10$H3X3efz02RonlvNXaRPr2eEbflSiFK1ITFdbyT2igUGDK9gDpIJqO",
     "createdAt" : ISODate("2020-03-09T13:50:23.702Z"),
     "updatedAt" : ISODate("2020-03-09T13:50:23.702Z"),
     "__v" : 0 

还有帖子文件:

 
    "_id" : ObjectId("5e66498ccaf5d6697ca3fdbd"),
    "title" : "Jimmy Page's post",
    "description" : "This is Jimmy Page's post",
    "user" : ObjectId("5e66496fcaf5d6697ca3fdbc"),
    "createdAt" : ISODate("2020-03-09T13:50:04.840Z"),
    "updatedAt" : ISODate("2020-03-09T13:50:04.840Z"),
    "__v" : 0 




     "_id" : ObjectId("5e6649b5caf5d6697ca3fdbf"),
     "title" : "Axl Rose's Post",
     "description" : "This is Axl Rose's Post",
     "user" : ObjectId("5e66499fcaf5d6697ca3fdbe"),
     "createdAt" : ISODate("2020-03-09T13:50:45.751Z"),
     "updatedAt" : ISODate("2020-03-09T13:50:45.751Z"),
     "__v" : 0 



     "_id" : ObjectId("5e664b7bf120ab6c0d9999c9"),
     "title" : "Jimmy Page's second post",
     "description" : "This is Jimmy Page's second post\n\n",
     "user" : ObjectId("5e66496fcaf5d6697ca3fdbc"),
     "createdAt" : ISODate("2020-03-09T13:58:19.261Z"),
     "updatedAt" : ISODate("2020-03-09T13:58:19.261Z"), 
     "__v" : 0 

【问题讨论】:

【参考方案1】:

您可以使用以下方法获取用户信息和他/她的帖子。

getUserPosts: async (req, res) => 
  try 
    const user = await User.findById(req.params.id).populate("posts");

    if (!user) 
      return res.status(400).json( error: "No user" );
    

    return res.status(200).json( user );
   catch (err) 
    return res.status(500).json( error: "Server error" );
  
;

【讨论】:

我收到的帖子仍然是空的。我必须在某处添加帖子 ID。我阅读了其他一些答案,但我不知道如何在这里获取帖子 ID。 @ubuntu7788 你如何为帖子收集创建模型?一定是这样的mongoose.model("Posts", postSchema )。这里的帖子必须与这里的帖子匹配 ref: "Posts" 我的猫鼬模型是export const Post = mongoose.model("Post", postSchema, "posts")。我不知道为什么需要第三个参数 "posts"。这是可选的,对吧? @ubuntu7788 你需要在用户模式中像posts:[ type: Schema.Types.ObjectId, ref: "Post" ] 这样更改你的引用。我们对第三个参数不感兴趣。 @ubuntu7788 不客气,能否将其标记为答案并点赞?

以上是关于使用猫鼬填充时返回一个空的帖子数组的主要内容,如果未能解决你的问题,请参考以下文章

如何在子文档中填充模型实例数组? MongoDB猫鼬

当填充涉及猫鼬时如何返回文档内容数组

构建我的猫鼬模式的最佳方式:嵌入式数组、填充、子文档?

猫鼬填充返回空数组

Mongoose 静态方法填充数组

如何让猫鼬将一组 url 推送到数组子文档