I'm trying to write a Eshop Application and I want to get total price of a product multiplied by the product count using virtuals
this is my "cart-item" schema
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";
});
how can i get the product price and get from the virtual ?
You can use just a this.price
productSchema.virtual("price").get(function () {
return this.price * something; // You price calculations;
});
virtual
works with current data instance, after it initialisation. Any asyncronouse oprations must be completed before virtual usage. This is just a sugar code, which works with ready to use data
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.