根据另一个集合猫鼬更新集合上的虚拟字段

时间:2020-07-25 09:09:25

标签: node.js mongodb express mongoose

我有2个收藏集,分别称为Post and Likes。 Likes Schema包含用户和帖子,

const likesSchema = mongoose.Schema({
 post: {
  type: mongoose.Schema.ObjectId,
  ref: 'Post',
 },
 user: {
  type: mongoose.Schema.ObjectId,
  ref: 'User',
 },
});

我在发布架构中有一个虚拟字段,称为“ isLiked”,应根据Like集合进行更新。如果当前用户喜欢某个帖子,则应该更新该帖子集合中的虚拟“ isLiked”字段,

postSchema.virtual('isLiked').get(function () {
 //here I want to check if the current user liked the post and return true or false.
 return false;
});

但是在上面的代码片段中,我无法通过req.user获取当前用户。那么如何在发布架构中更新虚拟字段?

下面是我的控制器功能,用于获取帖子和得到的回复,

getAllPosts

exports.getAllPost = catchAsync(async (req, res, next) => {
 req.user.userFollows.push(req.user.id);
 const filter = { user: { $in: req.user.userFollows } };
 const post = new Post();
 post.currentUser = req.user;

 const features = new APIFeatures(Post.find(filter), req.query)
   .filter()
   .sort()
   .limitFields()
   .paginate();

 const doc = await features.query;

 res.status(200).json({
   status: 'success',
   results: doc.length,
   data: {
     post: doc,
   },
  });
});

响应,

{
  "status": "success",
  "results": 1,
  "data": {
      "post": [
          {
            "createdAt": "2020-07-06T15:28:13.043Z",
            "media": [
                "post-1594049615540-113372115.png"
            ],
            "likesCount": 1,
            "commentsCount": 4,
            "tags": [
                "trophy"
            ],
            "_id": "5f034450b71bac355d960314",
            "description": "Trophies #trophy",
            "user": {
                "_id": "5eef61592561923e00bd05ad",
                "name": "Arthur Morgan"
            },
            "id": "5f034450b71bac355d960314",
            "isLiked": false
          }
      ]
    }
  }

0 个答案:

没有答案