![](/img/trans.png)
[英]Mongoose find.where in a schema with an attribute of type ObjectId
[英]Mongoose Model find using an attribute from anohter Schema
基本上我有2個模式。
用戶和帖子。
用戶有一個數組,其中包含來自帖子的 _ids。 並且 post 有一個屬性,告訴他是否是一個活躍的帖子。 -> is_active。 所以,我想過濾至少有一個活動帖子的用戶。
用戶模式
const UserSchema = new Schema(
{
name: {
type: String,
trim: true,
required: true
},
posts: [
{
type: Schema.Types.ObjectId,
ref: 'Post'
}
],
created_at: {
type: Date,
required: true,
default: Date.now()
}
}
)
export default mongoose.model<User>('User', UserSchema)
后架構
const postSchema = new Schema(
{
name: String,
is_active: boolean
}
)
你可以試試這個:
Users.aggregate([
{
$lookup: {
from: "Posts",
let: { postIds: "$posts", },
pipeline: [
{
$match: {
$expr: {
$and: [
{
$in: [ "$_id", "$$postIds" ]
},
{
$eq: [ "$is_active", true ]
},
]
}
},
},
// You can remove the projection below
// if you need the actual posts data in the final result
{
$project: { _id: 1 }
}
],
as: "posts"
}
},
{
$match: {
$expr: {
$gt: [ { $size: "$posts" }, 0 ]
}
}
}
])
你可以在這里的操場上測試它
我不確定您的應用程序的查詢要求,但您可以在 Posts 集合中的_id
和is_active
屬性上添加 復合索引,以加快查詢速度。
您可以在此處閱讀有關 MongoDB 數據聚合的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.