什么是查找所有记录的最佳方式,Post
说,然后只标记属于登录用户的帖子带有一些标志(假设帖子可以属于许多用户)。理想情况下,我希望这在服务器上发生,所以如果我有Post.find({})
的100个帖子,我可以获得Mongoose文档或JSON对象,如下所示:
[{title: "some Post", userPost: true}, {title: "another post}, {title: "third post", userPost: true}, {title: "Last post"}]
在这个结果中,我可以以特定的方式装饰用户帖子。但是,我想查询所有帖子,但只查询用户帖子,并且因为这不是通过模板引擎,我需要在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});
} );
} );
有关改进的建议吗?这个过滤器功能应该在Post模型上吗?在初始查询中有更有效的方法吗?我知道Mongoose中的lean()
将返回JSON而不是Mongoose文档,所以我不需要进行转换。我很开心。
我想在这些方面做点什么:
//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;
});
})
});