【问题标题】:How to use virtual on a nested field in mongoose如何在猫鼬的嵌套字段上使用虚拟
【发布时间】:2022-02-08 20:55:55
【问题描述】:

我在 node.js 中使用猫鼬。我有以下架构。

const CustomerSchema = new mongoose.Schema({
    ...
    email: {
        type: String,
        required: true,
        lowercase: true,
        trim: true
    },
    addresses: [
        {
            addressType: { 
                type: String,
                enum: [ 'personal', 'shipping', 'billing' ]
            },
            street: {
                type: String,
                required: true,
                trim: true
            },
            streetNumber: {
                type: String,
                trim: true
            },
            floor: {
                type: String,
                trim: true
            },
            apartament: {
                type: String,
                trim: true
            },
            cp: {
                type: String,
                required: true,
                trim: true
            },
            district: {
                type: String,
                trim: true
            },
            city: {
                type: mongoose.Schema.ObjectId,
                ref: 'City',
                required: true
            }
        }
    ]

});

我想使用 "virtuals" 在数组地址中的每个对象中“添加”一个新字段

我如何使用虚拟来做到这一点?有可能吗?

我可以使用相同的结果,但我想使用 virtuals。

const customerDB = await Customer.findById(idCustomer).lean()

        customerDB.addresses = customerDB.addresses.map((address) => ({
            ...address,
            addressDesc: mapTypeAddressDescription(address.addressType)
        }));

非常感谢!

【问题讨论】:

  • 我最近回答了类似的问题。也许你想看看它,关于如何创建一个高效的文档 - stackoverflow.com/questions/71013664/…
  • @SomeoneSpecial 您好,感谢您的回复。我阅读了您的答案,这是有道理的,但在这种情况下,我看到将地址存储在 Customer 集合中。我可以将它分成不同的集合,但我不确定它的好处。

标签: node.js mongodb mongoose


【解决方案1】:

顾名思义,virtuals 不会添加到 MongoDB 文档中。它们用于文档的计算属性。

假设您有一个用户模型。每个用户都有一封电子邮件,但您还需要该电子邮件的域。例如,“test@gmail.com”的域部分是“gmail.com”。

以下是使用虚拟实现域属性的一种方法。您可以使用 Schema#virtual() 函数在架构上定义虚拟变量。

const userSchema = mongoose.Schema({
  email: String
});
// Create a virtual property `domain` that's computed from `email`.
userSchema.virtual('domain').get(function() {
  return this.email.slice(this.email.indexOf('@') + 1);
});
const User = mongoose.model('User', userSchema);

let doc = await User.create({ email: 'test@gmail.com' });
// `domain` is now a property on User documents.
doc.domain; // 'gmail.com'

您应该查看documentation 了解更多详情。

你可以这样做:

CustomerSchema.path('addresses').schema.virtual('fullAddr').get(function() {
  return 'foo'
})

此外,如果上述答案不起作用,请在stackoverflow 上查看此答案。

【讨论】:

  • 您好,感谢您的回复。我不确定我是否足够清楚。我想在地址数组中使用这个“计算属性”。我不能这样做: virtual('addresses.myProperty').get(function() { return 'foo'; });我不知道虚拟机是否可行。
  • 更新了答案检查一下。
猜你喜欢
  • 2013-10-07
  • 2023-03-31
  • 1970-01-01
  • 2016-06-20
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 2021-01-09
相关资源
最近更新 更多