如何执行深层猫鼬?

问题描述 投票:0回答:3

这是我的question.js和user.js模式模型,其猫鼬如下所示,任何人都可以帮助使用Node js填充likes:[]数组对象中的所有用户名列表,因为我将近两个星期都面临这个问题,我无法从喜欢的用户中填充用户名。拜托,我感谢您的建议。

question schema model

user schema model

node.js mongoose-schema mongoose-populate
3个回答
1
投票

我尝试了您的代码,并使其在您的模型中正常工作。如果仅使用user,则可以直接调用.populate("user"),但是如果嵌套,则需要执行.populate("likes.user")

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

0
投票

[是的,谢谢Ratnadeep Bhattacharyya,现在我可以在点赞数组对象中填充用户名,并且还可以返回唯一的点赞数组。下面是工作代码:快乐编码,乔恩

//@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' });
  }
});

0
投票

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

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

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

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

或在哪里使用,如果点赞字段丢失或为空,则此处可能会出错,因此请检查是否存在

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

所以请使用存在的位置

Post.find( {likes: {$exists:true}, $where:'this.likes.length>0'} )
© www.soinside.com 2019 - 2024. All rights reserved.