【问题标题】:How to fetch the value of a key for all the index in an array of objects如何获取对象数组中所有索引的键值
【发布时间】:2021-03-17 07:19:27
【问题描述】:

我想访问所有索引的 cart.item 以从 products 集合中获取值以获取产品的当前价格。

 const CartSchema = mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        required: true
    },
    cart: [
        {
        item: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'product'
        },
        quantity: {
            type: Number,
            required: true,
            default: 1
        },
        image: {
            type: String,
            required: true
        },
        name: {
            type: String,
            required: true
        }
    }
],
    active: {
        type: Boolean,
        default: true
    },
    modifiedOn: {
        type: Date,
        default: Date.now
    }
},
{ 
    timestamps: true 
});

这就是我的购物车架构的外观。我想像访问数组中的所有 cart.item 一样(显然不是这样)。我想将它与 Product 集合结合起来,以获取购物车中商品的当前价格,以计算总和和退货总额。购物车项目中的本地字段是 cart.item,而外部字段是产品架构中的 _id

const ProductSchema = mongoose.Schema({
    title: {
        type: String,
        required: true,
        index: true
    },
    category: {
        type: String,
        required: true,
        index: true
    },
    inStock: {
        type: Number,
        required: true
    },
    price: {
        type: Number,
        required: true
    }
});

const Products = mongoose.model('product', ProductSchema);

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    我想你想填充购物车项目 方法如下:

    在你的 find() 函数中

    Cart.find({}).populate('cart.item'))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      相关资源
      最近更新 更多