首页 > 解决方案 > 有条件地填充猫鼬

问题描述

我面临一个问题Mongoose。我有多个模型:

我正在尝试获取交易。

每个 Transaction 包含 asenderWalletId和 areceiverWalletId具有referenceto Wallet

钱包有一个名为or的字段,以及一个type包含对 a或 an的引用的字段。我通过指向同一个钱包的属性值的引用路径来实现这一点,就像这样。OrganizationUserownerUserOrganizationtype

type: {
    type: String,
    enum: [
      'User',
      'Organization',
      'Moneypot',
    ],
  },
  owner: {
    type: Schema.Types.ObjectId,
    refPath: "type"
  }

现在,我想填充ownerofreceiverWalletIdsenderWalletId。如果类型是Organization,我想检索namephoneNumberemail。如果类型是User,我想检索firstNamelastNmaeemailphoneNumber。我通过这段代码部分实现了这一点:

.populate({
      path: 'senderWalletId',
      select: ['owner', 'type'],
      match: { type: { $eq: 'User' } },
      populate: {
        path: 'owner',
        select: ['firstName', 'lastName', 'phoneNumber', 'email']
      }
    })
    .populate({
      path: 'receiverWalletId',
      select: ['owner', 'type'],
      match: { type: { $eq: 'User' } },
      populate: {
        path: 'owner',
        select: ['firstName', 'lastName', 'phoneNumber', 'email']
      }
    })

现在的问题是,如何让这些种群检索 name而不是当类型等于firstNamelastNameorganization

标签: node.jsmongodbmongoosemongoose-populate

解决方案


我通过将所有属性放入选择数组中找到了解决方法,如下所示:

   .populate({
      path: 'senderWalletId',
      select: ['owner', 'type'],
      match: { type: { $eq: 'User' } },
      populate: {
        path: 'owner',
        select: ['name', 'firstName', 'lastName', 'phoneNumber', 'email']
      }
    })
    .populate({
      path: 'receiverWalletId',
      select: ['owner', 'type'],
      match: { type: { $eq: 'User' } },
      populate: {
        path: 'owner',
        select: ['name', 'firstName', 'lastName', 'phoneNumber', 'email']
      }
    })

NoSQL 的强大功能现在开始使用,因为返回的数组包含钱包类型为firstName的情况下,它包含的情况下为lastNameUsernameorganization


推荐阅读