如何使用猫鼬虚拟将一个文档的内容显示到另一个文档中

问题描述

我正在尝试编写一个 Eshop 应用程序,我想使用 virtuals

将产品的总价格乘以产品数量

这是我的“购物车项目”架构

const cartItem = new Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,ref: "user",},products: [productSchema],{ timestamps: true }
); 

//Product Schema
const productSchema = new Schema({
  productId: { //ref to Product Schema,[simple schema with name,price and properties ]
    type: mongoose.Schema.Types.ObjectId,ref: "product",quantity: {
    type: Number,default: 1,required: true,});

productSchema.virtual("price").get(function () {
 const price = **// How to get price from "productId" and return as virtual**
  return "virtual";
});

如何获取产品价格并从虚拟获取

解决方法

您可以只使用 this.price

productSchema.virtual("price").get(function () {
   return this.price * something; // You price calculations;
});

virtual 在初始化后处理当前数据实例。任何异步操作都必须在虚拟使用之前完成。这只是一个糖代码,适用于随时可用的数据