【发布时间】: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
【问题讨论】: