簡體   English   中英

貓鼬找到所有然后標記與用戶ID匹配的文檔

[英]Mongoose find all then mark documents that match User ID

“找到所有記錄的最佳方法是什么?” Post ,然后用一些標志僅標記屬於已登錄用戶的帖子(假設一個帖子可以屬於多個用戶)。 理想情況下,我希望這種情況在服務器上發生,因此,如果我總共有100個Post.find({})帖子, Post.find({})可以得到如下所示的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;
         });
    })
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM