繁体   English   中英

如何执行人口密集的猫鼬?

[英]How to perform deep populate mongoose?

这是我的 question.js 和 user.js 模式模型,带有 mongoose,如下所示,任何人都可以帮助如何使用 Node js 填充 likes:[] 数组对象中的所有用户名列表,因为我现在面临这个问题将近 2 周了,我无法从喜欢的用户填充用户名。 拜托,我很感激你的建议。

问题模式模型

用户模式模型

我尝试了您的代码并使用您的模型使其正常工作。 如果你只使用user你可以直接调用.populate("user")但如果它嵌套你需要做.populate("likes.user")

Post.findOne( { _id: id } ).populate( "user" ).populate( "likes.user" );

要填充用户详细信息,请使用

Post.findOne( { _id: id } )
    .populate( "user" )
    .populate( "likes.user" );

要获得喜欢的帖子,请使用

Post.find({ "likes": { "$gt": 0 } }, function(err, data) {
})

或使用 where,如果喜欢字段缺失或为空,这里可能会出错,所以请检查它是否存在

Post.find( {$where:'this.likes.length>0'} )

所以请使用 where 和 exists

Post.find( {likes: {$exists:true}, $where:'this.likes.length>0'} )

是的,感谢 Ratnadeep Bhattacharyya,现在我能够在喜欢数组对象中填充用户名,并且还能够返回唯一的特定喜欢数组。 以下是工作代码:Happy Coding, Jonh

//@route api/post/get/likes
router.get('/get/likes/:postId', auth, async (req, res) => {
  try {
    //check if post exist
    const likes = await Post.findOne({ _id: req.params.postId })
      .populate('user', ['name'])
      .populate('likes.user', ['name']);
    return res.status(200).json(likes.likes);
  } catch (error) {
    console.log(error.message);
    res.status(500).json({ msg: 'Server error' });
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM