const followingUsers = await User.find({ _id: { $in: foundUser.followings } })
const getFeedData = async() => {
let data = []
for (let user of followingUsers) {
const userPosts = user.posts
for (let post of userPosts) {
const posts = await Post.find({ _id: post })
for (let post of posts) {
const foundPost = await Post.findById(post._id).sort({ createdAt: -1 })
data.push(foundPost)
}
}
}
return data
}
const posts = await getFeedData()
這是一些示例資料,假設有兩個相同的用戶,我想獲取他們的帖子并按升序對它們進行排序,這兩個用戶是我關注的用戶,我需要獲取他們的所有帖子并在新聞提要中顯示它們
"user": [
{
_id: ObjectId("625c053cfdd023e3713b297f"),
email: "[email protected]",
isAdmin: false,
chats: [],
blockedChats: [],
feedback: [],
plans: [],
posts: [
ObjectId("625c0577fdd023e3713b29c7"),
ObjectId("625c0582fdd023e3713b29f5"),
ObjectId("625c075f8f794ea1fcf6c6af"),
ObjectId("625c4a742db74795a43d5243")
],
opportunities: [],
username: "sam",
createdAt: ISODate("2022-04-17T12:17:01.095Z"),
updatedAt: ISODate("2022-04-17T17:12:20.341Z"),
__v: 4
}
],
"post": [
{
_id: ObjectId("625c0577fdd023e3713b29c7"),
postText: "hi this is sam\r\n",
likes: [],
likesCount: [],
timePosted: ISODate("2022-04-17T12:09:05.535Z"),
postImage: [],
user: ObjectId("625c053cfdd023e3713b297f"),
createdAt: ISODate("2022-04-01T00:00:00.00Z")
},
{
_id: ObjectId("625c075f8f794ea1fcf6c6af"),
postText: "it works !!!",
likes: [],
likesCount: [],
timePosted: ISODate("2022-04-17T12:20:08.794Z"),
postImage: [],
user: ObjectId("625c053cfdd023e3713b297f"),
createdAt: ISODate("2022-04-17T12:26:07.075Z"),
updatedAt: ISODate("2022-04-17T12:26:07.075Z")
}
]
蒙古游樂場
一切正常,除了我檢索回來的檔案不是按升序排列的,這也可能是由于回圈,或者可能對資料庫執行盡可能少的查詢,這里有什么問題可以幫忙嗎?
uj5u.com熱心網友回復:
您可能可以通過$lookup.
const getFeedData = async() => {
const foundPost = await User.aggregate([
{
$match: {
_id: {
$in: foundUser.followings
}
}
},
{
"$lookup": {
"from": "post",
"let": {
posts: "$posts"
},
"pipeline": [
{
$match: {
$expr: {
"$in": [
"$_id",
"$$posts"
]
}
}
},
{
"$sort": {
createdAt: -1
}
}
],
"as": "postLookup"
}
},
{
"$unwind": "$postLookup"
},
{
"$replaceRoot": {
"newRoot": "$postLookup"
}
}
])
return foundPost
}
const posts = await getFeedData()
這是Mongo游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/460148.html
標籤:节点.js mongodb 表示 猫鼬 mongodb查询
下一篇:使用mongoose查找多個檔案
