如何架构一个需要在mongoDB上过滤的引用文档?

问题描述 投票:0回答:1

我有一个用户文档和一个事务文档。

  • 事务有一个所有者(用户)。
  • 用户有一组没有限制增长的交易。

我需要得到用户的交易,并通过一些属性进行过滤,比如,日期范围和支付或未支付。

由于我的交易Schema是无限制的,我使用mongoose virtuals来填充用户的交易,但是我看到它不可能对一个虚拟的交易进行MongoDb查询,因为它并不真正在数据库中。

的使用模式。

const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
      trim: true,
      unique: true,
    },
    ...
  },
);

userSchema.virtual('transactions', {
  ref: 'Transaction',
  localField: '_id',
  foreignField: 'owner',
});

事务模式。

const transactionSchema = new Schema({
  amount: {
    type: Number,
    required: true,
  },
  ...
  owner: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
});

我觉得我这样建模数据库的时候犯了一些错误。这种情况下,哪种方法是最好的?

mongodb mongoose mongoose-populate
1个回答
0
投票

我不认为在这里使用virtuals是个好主意。你在你的事务模型里有用户参考,这就够了。你可以用mongo查询任何你喜欢的东西 聚集你可以在交易收集上进行汇总,并使用 $lookup (如上所述 此处)来填充用户或查询用户。

© www.soinside.com 2019 - 2024. All rights reserved.