【发布时间】: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