mongoose - 如何使用 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()
}
我在这里引用了文档(以及其他内容),但我似乎找不到我做错了什么——它似乎应该返回一个数字?
谢谢!
解决方案
推荐阅读
- java - 使用 ProcessBuilder 结果填充 JavaFX listView
- scala - 处理数据倾斜而不加盐火花中的连接键
- tensorflow - GlobalAvgPool1D 与输出大小不兼容
- swift - 如何使 Rectangle() 和 DatePicker 重叠?
- node.js - 打字稿:'数字| undefined' 不可分配给“number”类型的参数
- java - java URLConnection - 如何从包含大写字母的 URL 中读取数据?
- reactjs - 使用 react-i18next 补水 SSR React App 导致闪烁
- android - 在终端的后台运行 android builds/gradle?
- linux - Linux复制具有特定文件名长度的所有文件
- json - Flutter - 带有 Dart 的通用 json 序列化器