首页 > 解决方案 > 如何使用 Mongoose 虚拟的价值?

问题描述

我有一个包含购物车的用户模式,它是一个对象数组,其中包含来自 Jam 模式的 jamId 和数量。我正在尝试创建一个返回购买总价的虚拟。

const User = new Schema(
  {
    cart: [
      {
        jamId: { type: Schema.Types.ObjectId, refs: "jams" },
        quantity: { type: Number, required: true },
      },
    ],
  },
  { timestamps: true, toJSON: { virtuals: true }, toObject: { virtuals: true } }
)

User.virtual('subtotal').get(async function () {
  let total = 0
  for (let i = 0; i < this.cart.length; i++) {
    const jam = await Jam.findById(this.cart[i].jamId)
    total += Number(this.cart[i].quantity) * Number(jam.price)
  }
  //console.log(total)
  return total
})

当我记录虚拟功能内部的总数时,我得到了正确的总数。但是,当我尝试记录 user.subtotal 时,我得到一个空对象。我登录了用户,它似乎很好。

useEffect(() => {
  const fetchUser = async () => {
    const user = await getUser(props.user.id)
    //this gives an empty object instead of a number
    console.log(user.subtotal)
  }
  fetchUser()
}

我在这里引用了文档(以及其他内容),但我似乎找不到我做错了什么——它似乎应该返回一个数字?

谢谢!

标签: mongoosemongoose-schema

解决方案


推荐阅读