Search code examples
mongodbmongoosemongodb-querymongoose-schemamongoose-populate

Query for Schema of Schemas


I have two schemas here, User and Connection. A User schema has an email, name, and password. A Connection schema is the one in which UserID is equal to the _id of a User, hasRequested - an array that consists of _id's of Users that have requested to connect & isConnection - an array that has the _id of a User(s) that are connected to the User. Suppose there is a user with _id A, and has two connections(with _id B and C). And suppose B has connections A,X,Y. And suppose C has connections A,M,N. What MongoDB query should I write so that I can get the connections of A, along with the connections of B and C or simply say connection of connections

Schemas --->>

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true
    }
}, { timestamps: true });
const ConnectionSchema = new mongoose.Schema({
    UserID: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        required: true
    },
    hasRequested: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }],
    isConnection: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }]
})

Solution

  • Unfortunately there is no way to nested populate between these documents. You should make separated request to achieve this goal. However if you combine them like:

    const UserSchema = new mongoose.Schema(
      {
        name: {
          type: String,
          required: true,
        },
        email: {
          type: String,
          required: true,
        },
        password: {
          type: String,
          required: true,
        },
        hasRequested: [
          {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
          },
        ],
        isConnection: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        }]
      },
      { timestamps: true }
    );
    

    Then you may use this query to get your wanted request:

    await User.findOne({ _id: userID }).populate(path = "hasRequested", populate = "hasRequested");