How to do reverse nested query in mongoose

Viewed 99

I have two models:

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,
    }
})

I know I can query a single Post like:

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

But how do I query a user with all the posts? I know I could do two seperate queries and put them together, but is there a way to do this with the mongoose api itself?

1 Answers

in this case you should inverse schemas as :

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

and query a user with all the posts as :

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

or use aggregate method as :

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