【问题标题】:how to display content of a document into another document using mongoose virtual如何使用猫鼬虚拟将文档的内容显示到另一个文档中
【发布时间】:2021-09-27 21:41:45
【问题描述】:

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

获得产品总价乘以产品数量

这是我的 "cart-item" 架构

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";
});

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

【问题讨论】:

    标签: javascript node.js mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    您可以只使用this.price

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

    virtual 在初始化后与当前数据实例一起工作。任何异步操作都必须在虚拟使用之前完成。这只是一个糖代码,适用于即用型数据

    【讨论】:

    • 我不明白,我想从 productId -- ref of --> product 文档中获取价格,没有 price 架构中的字段
    猜你喜欢
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2022-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2019-12-20
    相关资源
    最近更新 更多