首页 > 解决方案 > 尝试将产品添加到 NodeJS 中的列表(“TypeError undefined”)

问题描述

我刚刚开始使用 NodeJS,所以我处于初学者水平。我正在尝试使用 MongoDB 构建一个购物清单应用程序,用户在其中登录,创建一个列表,然后将项目添加到该列表中。我可以注册并登录并创建一个列表,但是当我尝试向其中添加项目时,我遇到了这个问题:“TypeError:无法读取未定义的属性'产品'”。它的代码是:

    const user = req.user;
    const shoppinglist_id = req.body.shoppinglist_id;
    const name = req.body.name;

    let new_product = product_model({
        title: req.body.title,
        imagePath: req.body.imagePath,
        quantity: req.body.quantity
    });
    new_product.save().then(() => {
        shoppinglist_id.products.push(new_product);
        console.log('product saved');
        shoppinglist_id.save().then(() => {
            return res.redirect('/');
        });
    }); ```

User model:
const user_schema = new Schema({
    name: {
        type: String,
        required: true
    },
    shoppinglists: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'shoppinglist',
        req: true
    }]
});

Shoppinglist model:
const shopping_list_schema = new Schema({
    name: {
        type: String,
        required: true
    },
    products: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'product',
        req: true
    }]
});

Product model:
var schema = new Schema({
   imagePath: {type: String, required: true}, 
   title: {type: String, required: true},
   quantity: {type: Number, required: true}
});

知道我做错了什么吗?我知道问题出在这一行:“shoppinglist_id.products.push(new_product);”,我已经尝试了所有方法,“user.shoppinglists.products”等。没有任何效果。有什么帮助吗?

编辑:我还将发布我的添加购物清单作为参考,它工作正常。

    const user = req.user;
    let new_shoppinglist = shopping_list_model({
        name: req.body.name,
        products: req.body.products
    });
    new_shoppinglist.save().then(() => {
        console.log('shoppinglist saved');
        user.shoppinglists.push(new_shoppinglist);
        user.save().then(() => {
            return res.redirect('/');
        });
    });
}```


EDIT #2:
I am adding how I am getting to shoppinglist-view:
´´´
const get_shoppinglist = (req, res, next) => {
    const shoppinglist_id = req.params.id;
    shopping_list_model.findOne({
        _id: shoppinglist_id
    }).then((shoppinglist) => {
        shoppinglist.populate('products')
        .execPopulate()
        .then((shoppinglist) => {
            let data = {
                shoppinglist: shoppinglist

            };
            console.log(data);
            let html = shoppinglist_views.shoppinglist_view(data);
            res.send(html);
        });
    });
};´´´

And shoppinglist-view:
´´´
const shoppinglist_view = ((data) => {
    let html = `
    <html>
    <body>
    <h1></h1>
    <h2>${data.shoppinglist.name}</h2>
    <h4><a href="/">Go back</a></h4>


    <br>
    `
     data.shoppinglist.products.forEach((product) => {
        html += products
         html += `
         <div>
         <p>
         <h2>Name of the shopping list: ${shoppinglists.shoppinglist.name}</h2>
         <h3> Name: ${product.title}<br></h3>
         <img src="${product.imagePath}" width="50px" height="50px" />
         quantity: ${product.quantity} </p>
         </div>
         </body>
         </html>
         `;
        });
        html += `
        <form action="/add-product" method="POST">
        <p>Add products</p><br>
        Title?<br>
            <input type="text" name="title"><br>
        Image-link<br>
            <input type="img" name="imagePath"><br>
        Quantity?<br>
            <input type="number" name="quantity"><br><br>
            <button type="submit">Add to list</button>
        </form>
        </html>
        </body>`;
         return html;
´´´

标签: node.jsmongodbmongoose

解决方案


这是因为shoppinglist_id未定义。目前,您得出这样的值:

const shoppinglist_id = req.body.shoppinglist_id;

换句话说,req.body没有名为 的属性shoppinglist_id。如果您打印 的值req.body,您很可能会看到它是一个字符串。如果您尝试发送/接收 JSON 数据(我猜您是),您必须首先解析请求正文:

const data = JSON.parse(req.body);
const shoppinglist_id = data.shoppinglist_id;

甚至更好:

const data = JSON.parse(req.body);
const { shoppinglist_id } = data;

请注意,您应该始终在try ... catch块中解析不受信任的 JSON,但这是另一天的另一课。


推荐阅读