我有 2 個集合,一個用于用戶,另一個用于帖子(帖子集合有 _id 的用戶作為發布者)。在用戶集合中,每個用戶都有朋友陣列,其中包含用戶的_id。我想按排序順序(按 CreatedAt 排序)獲取我的朋友和我的所有帖子。
這是我的用戶模式,其中我有朋友陣列的貓鼬物件型別參考用戶集合,這里我存盤用戶 id 誰是朋友。`//用戶架構
const userSchema = new Schema({
profileImg : {
type: String,
},
name: {
type: String,
required: [true, 'Please Enter Your Name!']
},
about: {
type: String,
},
email: {
type: String,
required: [true, 'Please Enter Email!'],
unique: [true, 'Already Registered!'],
match: [/\S @\S \.\S /, 'is invalid!']
},
password: {
type: String,
required: [true, 'Please Enter Your Password!'],
},
friends: [{
type: mongoose.Types.ObjectId,
ref: 'USER'
}],
address: {
line1: {
type: String,
required: [true, 'Please Enter Your Address!']
},
line2: {
type: String
},
city: {
type: String,
required: [true, 'Please Enter Your City!']
},
state: {
type: String,
required: [true, 'Please Enter Your State!']
},
}
}, { timestamps: true })
這是我的帖子模式,其中 userId 是用戶集合的參考,這里保存了上傳帖子的用戶的 _id。//POST SCHEMA
const postSchema = new Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "USER",
required: true
},
postImage: {
type: String,
required: [true, 'Please Upload the Image!']
},
caption: {
type: String
},
likes: [likeSchema],
comments: [commentSchema]
}, { timestamps: true })
`
我在做什么:
第一個我通過_id 找到用戶第二個從找到的用戶的朋友陣列中查找帖子集合以獲取朋友的帖子第三個現在再次獲取擁有的帖子在帖子集合中查找自己的_id第四個從朋友帖子和用戶獲得的兩個陣列發布為帖子
現在在第 4 步之后,我想按 createdAt 對帖子進行排序,但它不起作用.. 如何排序?
const posts = await User.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId(req.user_id)
}
},
{
$lookup: {
from: "posts",
localField: "friends",
foreignField: "userId",
as: "friendposts"
}
},
{
$lookup: {
from: "posts",
localField: "_id",
foreignField: "userId",
as: "userposts"
}
},
{
$project: {
"Posts": {
$concatArrays: ["$friendposts", "$userposts"]
},
_id: 0
}
}
])
uj5u.com熱心網友回復:
您可以使用 1 查找而不是 2 。對于排序,你有 3 種方法
- 在代碼級別排序(使用排序功能)
- 使用 $unwind $sort 和 group(如果 mongo db 版本小于 5.2)
- 使用$sortArray(適用于 mongodb 5.2 版本)
如果使用第二種方法。
User.aggregate([
{
'$match': {
'_id': mongoose.Types.ObjectId(req.user_id)
}
}, {
'$addFields': {
'users': {
'$concatArrays': [
'$friends', [
mongoose.Types.ObjectId(req.user_id)
]
]
}
}
}, {
'$lookup': {
'from': 'posts',
'localField': 'users',
'foreignField': 'userId',
'as': 'posts'
}
}, {
'$unwind': {
'path': '$posts'
}
}, {
'$sort': {
'posts.createdAt': -1
}
}, {
'$group': {
'_id': '$_id',
'posts': {
'$push': '$posts'
},
'name': {
'$first': '$name'
}
}
}
])
您可以添加最終回應中所需的任何其他欄位,就像我添加了名稱一樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452697.html
標籤:节点.js mongodb 猫鼬 mongodb查询 聚合框架
