如何根据mongoDB中的另一个集合字段更改集合中的字段

问题描述 投票:0回答:1

这是我的产品架构

const mongoose = require('mongoose');
    const productSchema = new mongoose.Schema({
        name: {
            type: String,
            required: true
        },
        price: {
            type: Number,
            required: true
        },
        create_at: {
            type: Date,
            default: Date.now,
            required: true
        },
        quantity: {
            type: Number, 
            required: true
        },
        brand: {
            type: String,
            default: '',
        },
        size: {
            type: String, 
        },
        images : {
            type : [String],
        },
        color: [{
            type: String, 
        }],
        description: {
            type: String, 
        },
        details: {
            type: String, 
        },
        category: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'category'
        },
        status: {
            type: Boolean,
            default: true,
            required: true
        },
        modified_at: {
            type: Date, 
            default: Date.now
        },
        deleted_at: {
            type: Date, 
        }
    }, {
        toJSON: { virtuals: true },
        toObject: { virtuals: true }
    });

这是我的报价架构

const mongoose = require('mongoose');
    const offerSchema = new mongoose.Schema({
        product: {
            type:mongoose.Schema.Types.ObjectId,
            ref: "Product",
        },
        category: {
            type:mongoose.Schema.Types.ObjectId,
            ref: "category",
        },
        offerType: {
            type: String,
            enum: [ "percentage", "price"],
        },
        offerValue: {
            type: Number,
        },
        startDate: {
            type: Date,
        },
        endDate: {
            type: Date,
        },
        description: {
            type: String,
        },
        createdAt: {
            type: Date,
            default: Date.now
        }
    });
    const offerModel = new mongoose.model("Offers", offerSchema );
    module.exports = offerModel;

我想根据offerModel更改产品的价格。如果产品有报价,那么价格应根据报价而变化。但它不应该在数据库中更新。当我在服务器端检索它时(一直),我需要更改它。

我在查询数据时使用两种方法来操作数据。

  1. 在猫鼬中使用虚拟方法。
productSchema.virtual('discountPrice').get( async function() {
        console.log('Inside the product schema virtual offer module');
        const offer = await offerModel.find({});
        console.log(offer);
        return this.price - 100;
    });

如果我不使用异步,它工作得很好。 virtual 不支持异步函数。 但它正在从数据库中获取数据。所以我不能在没有异步或承诺的情况下编写代码。结果是[对象承诺]而不是产品(当使用异步和承诺时)。

2.使用 pre('find') 它没有按我的预期工作。我不知道为什么。

productSchema.pre('find', async function() {
        const offer = await offerModel.find();
        console.log(offer);
        if(offer){
            this.price = this.price - 500;
            console.log(this.price)
        }else {
            console.log('error in pre find in product schema')
        }
    });

我在查询时收到了报价,但没有更改产品中的价格。

简而言之:我如何更改产品价格或添加新字段 disocutnPrice。价格应根据 OfferModel.js 中是否有特定产品或类别的报价而变化

mongodb asynchronous mongoose
1个回答
0
投票

由于您在

product
中存储了对
offerSchema
的引用,因此每当您执行
populate
时都可以
Product.find()
虚拟:像这样:

productSchema.virtual('offer', { 
   ref: 'Product', 
   localField: '_id', 
   foreignField: 'product' 
});

当您执行查询时,只需附加

populate
,如下所示:

const products = await Product.find().populate('offer');
const product  = await Product.findOne({name: 'Hat'}).populate('offer');

这会将一个由一个对象组成的数组添加到每个

Product
文档中。因此,要计算产品的
discountPrice
,您只需访问
0
offer
索引数组元素,如下所示:

productSchema.virtual('discountPrice').get(function() {
   // Implement logic to determine if offerType == percentage || price
   return this.price - this.offer[0].offerValue;
});
© www.soinside.com 2019 - 2024. All rights reserved.