【问题标题】:mongoose: Best way to get values for an object before save猫鼬:保存前获取对象值的最佳方法
【发布时间】:2019-11-30 01:11:26
【问题描述】:

我需要访问一个属性,但发送的只是 id。

我的请求正文示例:

{
"items": [
    {
        "quantity": 3,
        "product": "5d33fc0ac8c7a56d62cd6ac6"
    }
],
"user": "5d33fdafc8c7a56d62cd6ac9"

}

我需要得到产品的价格并乘以数量

async create(createOrderDto: CreateOrderDto): Promise<IOrder> {
try {
        const order = new this.orderSchema(createOrderDto);
        order.items.map(item => item.subtotal = item.product.price * item.quantity));
        return await this.orderSchema.create(order);
    } catch (error) {
        throw new InternalServerErrorException(error.message);
    }
}

item.product.price 错误消息:“属性 'price' 在类型 'ObjectId'.ts(2339)'上不存在”

如何将 item.product 转换为 Product.Schema 之类的?

【问题讨论】:

    标签: javascript node.js mongodb typescript nestjs


    【解决方案1】:

    这是因为map 将用给定函数的返回值替换列表元素,在您的情况下为item.product.price * item.quantity。您希望将item 作为返回值。


    考虑

    let items = [{price: 3, quantity: 2}];
    items = items.map(item => item.subtotal = item.price * item.quantity)
    

    那么items 将是[6]

    您应该这样做:

    let items = [{price: 3, quantity: 2}];
    items = items.map(item => {
        item.subtotal = item.price * item.quantity);
        return item;
    });
    

    这里items 将是[{price: 3, quantity: 2, subtotal: 6}]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 2018-07-12
      • 2017-04-27
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多