Home > front end >  mongoose query by foreign property
mongoose query by foreign property

Time:10-11

I have two tables, a user table and an order table. Now, if I want to query the orders of all the users whose appid is 1, how do I query them

const orderSchema = new mongoose.Schema({
    user: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: "User",
        required: true
    },
    orderNum: {
        type: String,
        required: true
    },
})
const UserSchema = new mongoose.Schema({
    nickname: String,
    avatarUrl: String,
    phone: String,
    appId: {
        type: String,
    }
});

CodePudding user response:

you can use aggregate to do that. https://mongoosejs.com/docs/api/aggregate.html

CodePudding user response:

You can use the following aggregation pipeline:

orderSchema.aggregate([
  {
    "$lookup": {
      "from": "User",
      "localField": "user",
      "foreignField": "_id",
      "as": "user"
    }
  },
  {
    $match: {
      "user.0.appId": "1"
    }
  }
])
  • Related