【问题标题】:How to implement a social media feed using MERNG?如何使用 MERNG 实现社交媒体提要?
【发布时间】:2020-02-16 18:28:38
【问题描述】:

我一直在从事一个基本上是社交媒体网站的项目。到目前为止,我构建的是用户可以创建帐户、创建帖子、相互关注、编辑他们的个人资料。关注的用户存储在一个数组中。每个帖子都有一个用户名字段,通过它我可以搜索该用户名发布的所有帖子。

我该怎么做才能对该数组中用户的最新帖子进行排序?

现在,我正在使用以下方式查询网站上发布的所有帖子:

    async getPosts() {
      try {
        const posts = await Post.find().sort({ createdAt: -1 });
        return posts;
      } catch (err) {
        throw new Error(err);
      }
    },

用户架构和发布架构都看起来像这样:

const userSchema = new Schema({
  name: {
    type: String,
    default: ""
  }, 
  username: {
    type: String,
    lowercase: true,
    unique: true,
    required: true
  },
  password: String,  
  email: {
    type: String,
    lowercase: true,
    unique: true,
    required: true
  },
  picture: {
    type: String,
    default: ""
  },
  createdAt: String,
  bio: {
    type: String,
    default: ""
  },
  website: {
    type: String,
    default: ""
  },
  gender: {
    type: String,
    default: ""
  },
  phone: {
    type: String,
    default: ""
  },
  followers: [{ username: String, createdAt: String}],
  following: [{ username: String, createdAt: String}]
});

const postSchema = new Schema({
  body: String,
  title: String,
  username: String,
  createdAt: String,
  category: String,
  comments: [
    {
      body: String,
      username: String,
      createdAt: String
    }
  ],
  likes: [
    {
      username: String,
      createdAt: String
    }
  ],
  user: {
    type: Schema.Types.ObjectId,
    ref: 'users'
  }
});

如果有人想查看项目目前的进度,请点击此链接:http://dev.divuture.com

【问题讨论】:

    标签: reactjs mongodb graphql


    【解决方案1】:

    按日期对数据数组进行排序:

    数据数组示例:

    let myPosts = [
      { ...
       createdAt: "2013/7/02"
       ...
       },
       { ...
         createdAt: "2013/01/01"
         ...
         },
         { ...
           createdAt: "2013/12/01"
           ...
           },
    ];
    

    排序函数

     function sortMe(a, b) {
        return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
      }
    

    //按日期排序所有帖子

      myPosts.sort(sortMe);
    

    阅读更多关于排序功能的信息 https://www.w3schools.com/jsref/jsref_sort.asp

    【讨论】:

    • 您没有理解我的问题,我当前的函数会进行排序。我需要一个函数,它只为那些用户名在以下数组中的用户加载一组帖子
    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 2014-10-12
    • 2020-08-14
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多