基于填充字段的虚拟

问题描述

我有一个购物车架构,例如

// Cart Schema
const CartSchema = new Schema(
    {
        products: [
            {
                type: Schema.Types.ObjectId,ref: "Product",},],}
);

我想根据填充的“产品”字段(也可能包含虚拟产品)对购物车进行一些计算。 虚拟的:

CartSchema.virtual("price").get(async function (this: CartDocument) {
    await this.populate("products").execPopulate();
    console.log(this.products); //Error: this.populate is not a function

    //Need to loop through the products' properties to calculate a total price and other things

    return {
        total: 0,tax: 0,};
});

我尝试在 CartSchema 的“产品”字段上使用 mongoose-autopopulate,但结果相同。在购物车的虚拟内部,填充的数据不显示

问题

  1. 我怎样才能做到这一点?也许我采取了不正确的方法,应该采取完全不同的做法?
  2. 我知道我可以执行 Cart.findOne() 然后遍历填充的产品字段并计算值,但我想要一个更优雅的解决方案,其中执行 Cart.findOne() 将自动包含使用 Virtual购物车架构中的字段。

注意:这个问题可能类似于this one。但我是这些的初学者,它没有任何答案,所以我想我会在这里问我的具体情况。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)