簡體   English   中英

Mongoose 關系 - 根據 userId 填充多個文檔

[英]Mongoose Relationship - Populate with multiple docs based on userId

只是想知道我們如何根據 userId 使用多個文檔填充查詢?

用戶模式

const UserSchema = new Schema({
    email: {
        type: String,
        unique: true,
        required: true,
    },
    hashValue: {
        type: String,
        required: true,
    },
}, options);

FooSchema

const FooSchema = new Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    posts: {
        type: String,
        required: true,
     },
}, options);

條形圖

const BarSchema = new Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    sharedPosts: {
        type: String,
        required: true,
     },
}, options);

我想要實現的是

User.find({})
     .populate('bar')
     .populate('foo')

結果應該是這樣的 json

{
  email: "x",
  hashValue: "x",
  foo: {...},
  bar: {...}
}

通過使用聚合解決

    User.aggregate([
            {
                $lookup: {
                    from: 'foos',
                    localField: '_id',
                    foreignField:  'user',
                    as: 'foo'
                  }
            },
            {
                $lookup: {
                    from: 'bars',
                    localField: '_id',
                    foreignField:  'user',
                    as: 'bar'
                  }
            },
            {
                $project: {
                    // properties to include in return (from User)
                    _id: 1,
                    email: 1,
                    hashValue: 1,
                    createdAt: 1,
                    updatedAt: 1,

                    //reutrn foo: {} instead of foo: []
                    foo:  { $first: "$foo" }, 

                    //reutrn bar: {} instead of bar: []
                    bar:  { $first: "$bar" } 
                }
            }
  ])

暫無
暫無

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

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