【问题标题】:Mongoose, populate boolean variable if ObjectId in array of document field returned from queryMongoose,如果从查询返回的文档字段数组中的 ObjectId 填充布尔变量
【发布时间】:2017-12-14 04:48:54
【问题描述】:

所以我有一个用户模型和一个帖子模型。一个用例是用户可以点赞帖子。

帖子架构包含我命名为“likers”(喜欢帖子的用户对象)的 ObjectID 数组

我想编写一个返回所有帖子的查询,但每个帖子都有一个额外的“喜欢”字段,该字段是基于登录用户 objectid 是否在“喜欢”数组中的布尔值。

我正在尝试的代码:

router.get("/posts", function(req, res, next) {
  Posts.find({})
    .then(posts => {
      posts = posts.map(post => {
        // How to write this so it works
        // test if req.user._id in likers which is Schema type [ObjectID]
        post.liked = req.user && (post.likers.indexOf(req.user._id) > -1);
        return post;
      });
      res.json(posts);
    })
    .catch(errorHandler(res));
});

【问题讨论】:

  • 所以你想重写你的代码?因为看起来你已经拥有的东西是有效的。
  • 不,我无法让它工作。可能与比较我无法弄清楚的 ObjectID 有关。
  • 也许 post.likers.map(String).indexOf(req.user.id) 基本上应该将您的数组转换为字符串并将其与字符串 id 进行比较。
  • 我以前从未这样做过,但也许更简洁的方法是将aggregate$addFields$cond 一起使用。
  • 我绝对不会选择 populate 路线,因为在您的情况下,这更昂贵且效率低下。您将查询每个帖子的帖子和所有相关用户。您所关心的只是比较 ObjectId。

标签: javascript node.js mongoose


【解决方案1】:

原来我将错误的 id 保存到 likers 数组中,Doh

【讨论】:

    猜你喜欢
    • 2021-01-02
    • 1970-01-01
    • 2017-04-20
    • 2016-05-09
    • 1970-01-01
    • 2021-03-03
    • 2014-07-01
    • 2013-07-06
    • 2020-11-21
    相关资源
    最近更新 更多