0

just wondering how are we going to populate a query with multiple docs based on userId?

UserSchema

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);

BarSchema

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

what I want to achieve is something like

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

and the result should be look like this json

{
  email: "x",
  hashValue: "x",
  foo: {...},
  bar: {...}
}
Koala
  • 352
  • 2
  • 7
  • 18
  • Where is `userId` in your schema? – Shivam Dec 29 '22 at 04:09
  • @Shivam foo and bar has "user" that is referenced to UserSchema, and UserSchema has default _id which is also passed to BarSchema, FooSchema – Koala Dec 29 '22 at 04:12
  • Does this answer your question? [Querying after populate in Mongoose](https://stackoverflow.com/questions/11303294/querying-after-populate-in-mongoose) – Shivam Dec 29 '22 at 04:18

1 Answers1

0

Solved by using aggregate

    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" } 
                }
            }
  ])
Koala
  • 352
  • 2
  • 7
  • 18