node.js - 有条件地填充猫鼬
问题描述
我面临一个问题Mongoose
。我有多个模型:
- 交易
- 钱包
- 用户
- 组织
我正在尝试获取交易。
每个 Transaction 包含 asenderWalletId
和 areceiverWalletId
具有reference
to Wallet
。
钱包有一个名为or的字段,以及一个type
包含对 a或 an的引用的字段。我通过指向同一个钱包的属性值的引用路径来实现这一点,就像这样。Organization
User
owner
User
Organization
type
type: {
type: String,
enum: [
'User',
'Organization',
'Moneypot',
],
},
owner: {
type: Schema.Types.ObjectId,
refPath: "type"
}
现在,我想填充owner
ofreceiverWalletId
和senderWalletId
。如果类型是Organization
,我想检索name
、phoneNumber
和email
。如果类型是User
,我想检索firstName
、lastNmae
、email
和phoneNumber
。我通过这段代码部分实现了这一点:
.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
而不是当类型等于firstName
lastName
organization
解决方案
我通过将所有属性放入选择数组中找到了解决方法,如下所示:
.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
的情况下,它包含的情况下为lastName
User
name
organization
推荐阅读
- mysql - Round() 函数在触发器内部的工作方式是否不同?
- spring-security - 如何即时更新 OPA 政策
- node.js - 快速重启节点服务器
- android - 无法从 AsyncTask 返回值;使用接口和委托;
- deep-learning - 如何在 MLM 和 NSP 的新域上从头开始训练 BERT?
- typo3 - TYPO3 9 的升级向导“slugs”因“出现问题”而失败
- java - 数学 java 处理弧球四元数三角,浮点舍入错误
- function - 不能从泛型元素上的迭代器构建泛型类型
- java - 是否可以选择 SQL 中的所有列但只选择每第三行?
- node.js - 如何从 Promise Sequelize 返回值