我一直在从事一个基本上是社交媒体网站的项目。到目前为止,我构建的是用户可以创建帐户,创建帖子,彼此关注,编辑其个人资料。关注的用户存储在数组中。每个帖子都有一个用户名字段,我可以通过该字段搜索该用户名发布的所有帖子。
我该怎么做才能对该阵列中用户的最新帖子进行排序?
现在,我正在使用以下方法查询网站上发布的所有帖子:
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
答案 0 :(得分:0)
要按日期对数据数组进行排序:
数据数组示例:
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);