【问题标题】:Populate without _id填充没有 _id
【发布时间】:2020-02-26 04:38:18
【问题描述】:

我有 2 个猫鼬模式,一个用于 stock(有关库存的信息),一个用于 trade。其中交易代表stock 的交易(如时间、交易量等)。每个stock 都有一个符号代码,我从中获取交易的数据馈送包括作为字符串的符号代码。我将如何填充这两个集合,因为我不能在这里使用常规的猫鼬'ref'

这是我的两个架构:

const stockSchema = new Schema({
  symbolCode: { type: String, trim: true },
  symbol: { type: String, trim: true },
  type: { type: String, index: true, trim: true },
  country: { type: String, lowercase: true }
})

 const tradeSchema = new Schema({
  symbolCode: { type: String, index: true },
  symbol: { type: String, index: true },
  price: Number,
  volume: Number,
  time: Date,
  currency: { type: String, default: 'USD', uppercase: true, index: true }
})

我想删除trade 架构中的前两个字段,以便我可以在这里对股票进行某种引用。我该怎么做?

【问题讨论】:

    标签: mongodb mongoose mongoose-populate


    【解决方案1】:

    像这样使用填充: MyModel.populate([{ path: 'author', select: 'username name -_id' }]);

    -fieldName 或在您的情况下为 -_id 将从投影中扣除它。

    【讨论】:

      【解决方案2】:

      为了将来参考,我使用populate virtuals 解决了这个问题,如下所示:

       stockSchema.virtual('trades', {
        ref: 'Trade',
        localField: 'symbolCode',
        foreignField: 'symbolCode',
        justOne: true
      })
      

      【讨论】:

      • 哇这个效果很好
      猜你喜欢
      • 2017-03-06
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 2017-06-09
      • 2016-04-06
      • 2016-02-14
      相关资源
      最近更新 更多