簡體   English   中英

如何在 mongoose 中進行反向嵌套查詢

[英]How to do reverse nested query in mongoose

我有兩個模型:

const UserSchema = new mongoose.Schema({
    username: String,
    name: String
})
const PostSchema = new mongoose.Schema({
    title: String,
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        required: true,
    }
})

我知道我可以查詢單個帖子,例如:

Post.findById(ID).populate('user')

但是如何查詢所有帖子的用戶? 我知道我可以做兩個單獨的查詢並將它們放在一起,但是有沒有辦法用 mongoose api 本身來做到這一點?

在這種情況下,您應該將模式反轉為:

const UserSchema = new mongoose.Schema({
    username: String,
    name: String,
    posts: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Post",
    ]}
})
const PostSchema = new mongoose.Schema({
    title: String,
})

並查詢所有帖子的用戶:

 User.findById(ID).populate('posts')

或使用聚合方法:

User.aggregate([
    { "$match": { "_id" : ID  }},
    { "$lookup": {
      "from": posts
      "let": { "userId":"$_id" },
      "pipeline": [
    { "$match": { "$expr": { "$eq": ["$user", "$$userId"] } } }
      ],
      "as": posts
    }}
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM