繁体   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