表示项目未定义

编程入门 行业动态 更新时间:2024-10-16 16:23:37

表示项目<a href=https://www.elefans.com/category/jswz/34/1771258.html style=未定义"/>

表示项目未定义

下面显示代码。

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const user = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    resetToken: String,
    resetExpiration: String,
    products: [{type: mongoose.Types.ObjectId, required: true, ref: 'Shop'}],
    cart: {
        items: [
            {
                productId: {type: mongoose.Types.ObjectId, ref: 'Shop', required: true},
                quantity: {type: Number, required: true},
            }
        ]
    },
});

user.methods.addToCart = (product) => {

    const itemIndex = this.cart.items.findIndex(prod => {
        return prod.productId.toString() === product._id.toString();
    });

    let newQuantity = 1;
    const updatedCartItems = [...this.cart.items];

    if(itemIndex >= 0) {
        newQuantity = this.cart.items[itemIndex].quantity + 1;
        updatedCartItems[itemIndex].quantity = newQuantity;
    } else {
        updatedCartItems.push({
            productId: product,
            quantity: newQuantity
        });
    }

    const updatedCart = {
        items: updatedCartItems
    }
    this.cart = updatedCart;
    return this.save();
}

const model = mongoose.model('User', user);

module.exports = model;

我尝试按照上述模式将产品存储在cart实例方法中,但是当我从控制器将产品发送到addToCart时,它说this.cart.items上的商品未定义。我在猫鼬中没有使用太多实例方法,所以我不知道这个问题是架构还是一般问题。

让我知道您是否需要其他信息。

回答如下:

这是一个愚蠢的错误,实际上我正在使用箭头功能。因此它没有绑定到架构。

更多推荐

表示项目未定义

本文发布于:2024-05-07 08:11:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755326.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未定义   项目

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!