我正在使用nestjs和mongodb創建一個api,一個社交網路,現在我正在創建一個名為“get posts”的路由,它用于獲取發出請求的用戶的朋友的帖子,我懷疑它確實如此不按時間順序回傳朋友的帖子
async friendsP(id: string) {
const user = await this.userModel
.findById(id, {
_id: false,
friends: true,
})
.catch(() => {
throw new HttpException('User not found', 404);
});
// If the id has the same characters as the normal id but does not exist
if (!user) {
throw new HttpException('User not found', 404);
}
const friends = user.friends;
const postsF = [] as Post[];
// This function makes a loop to grab the posts sent to the user and put them in a single json
const postFuntion = (posts: Post[]) => {
for (const post of posts) {
postsF.push(post);
}
};
// If there are friends
if (friends) {
for (const idF of friends) {
const posts = await this.postModel
.find({ userId: idF })
.populate('userId', {
_id: 0,
nickName: 1,
});
postFuntion(posts);
}
}
return postsF}
郵遞員還給我什么

抱歉沒有縮放,只有當我縮放 json 時才會完整顯示
問題是它沒有按時間順序排列它們,我想讓它們把新帖子放在最前面,但我不知道怎么做,有人可以幫我嗎?
我要提一下,我國現在時間是11:37
我試圖對postsF進行排序,但出現此錯誤

這是帖子的架構,可能有問題......
export type PostDocument = Post & Document;
type Image = {
url?: string;
public_id?: string;
};
@Schema()
export class Post {
@Prop({
type: [{ type: MongooseSchema.Types.ObjectId, ref: 'User' }],
})
userId: User;
@Prop({ type: Object, default: {} })
image: Image;
@Prop({ trim: true, default: '' })
description?: string;
@Prop({})
date: string;
}
export const PostSchema = SchemaFactory.createForClass(Post);
uj5u.com熱心網友回復:
這是一些代碼,可用于posts按日期按時間順序重新排序結果陣列:
function sortPosts(posts: Post[]) {
const prefixYMD = "1970-01-01 ";
posts.sort((post1, post2) => new Date(prefixYMD post1.date) - new Date(prefixYMD post2.date));
}
因為您的日期以小時 - 分鐘 - 秒的格式運行,所以您需要為年 - 月 - 日期添加前綴,最終可以是任何日期。
重要的是要注意,它會.sort 改變原始陣列,因此如果你愿意 - 你可以在分配poststo之前使用它postsF,或者在postsF. 您幾乎可以根據自己的需要對其進行定制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484647.html
