查找所有记录的最佳方式是Post.find({})
,然后仅标记属于已登录用户的帖子并带有一些标记(假设帖子可以属于许多用户)。理想情况下,我希望在服务器上发生这种情况,所以如果我有100条帖子[{title: "some Post", userPost: true}, {title: "another post}, {title: "third post", userPost: true}, {title: "Last post"}]
,我可以获得Mongoose文档或JSON对象,如下所示:
let currentUser;
Post.find().exec( ( error, posts ) => {
posts.map( ( p ) => {
let userPosted = currentUser.posts.some((userPost) => {
return userPost.equals(p._id)
});
return Object.assign(p.toObject(), {userPost: userPosted});
} );
} );
在此结果中,我可以以特定方式装饰用户帖子。但是,我想查询所有帖子,但只查询用户帖子,因为这不是通过模板引擎,我需要在JSON响应中存在标志以指示与当前用户的关系。
目前,我有一个如下所示的功能:
lean()
有关改进的任何建议吗?这个过滤器功能应该在Post模型上吗?在初始查询中有更有效的方法吗?我知道Mongoose中的<Wrapper>
<HeroBlock>
<h1>hi</h1>
<h4>hihi</h4>
</HeroBlock>
<IntroBlock>
<h1>heyyy</h1>
<h4>YO??</h4>
</IntroBlock>
<SkillsBlock>
<h1>Heyy</h1>
<h4>okkk</h4>
</SkillsBlock>
</Wrapper>
const Wrapper = styled.div`
display: grid;
grid-template-columns: 1fr;
`
const HeroBlock = styled.div`
background: skyblue;
height: 50vh;
-webkit-clip-path: polygon(0 0, 100% 0, 100% 90%, 0% 100%);
clip-path: polygon(0 0, 100% 0, 100% 90%, 0% 100%);
`
const IntroBlock = styled.div`
background: orange;
padding-bottom: 100px;
-webkit-clip-path: polygon(0 0, 100% 0, 100% 100%, 0% 90%);
clip-path: polygon(0 0, 100% 0, 100% 100%, 0% 90%);
`
const SkillsBlock = styled.div`
background: red;
-webkit-clip-path: polygon(0 0, 100% 0, 100% 90%, 0% 100%);
clip-path: polygon(0 0, 100% 0, 100% 90%, 0% 100%);
`
将返回JSON而不是Mongoose文档,因此我不需要进行转换。我很开心。
答案 0 :(得分:2)
我在假设这些方面的东西:
//first you need something associating the current user
const currentUser = ?;
const alteredPosts = [];
//get all posts from Mongo
Post.find({})
.exec(error, posts => {
if(error) console.error(error);
//search through all posts and find those by the current user
alteredPosts = posts.map( ( p ) => {
if(p._id === currentUser._id) {
p.currentUser = currentUser.id
}
return p;
});
})
});