【问题标题】:Cannot save data to MongoDB Compass无法将数据保存到 MongoDB Compass
【发布时间】:2021-09-22 16:33:17
【问题描述】:

我正在使用 Express 和 Mongo 学习 Nodejs。我在 Youtube 上看了一个教程,并尝试制作一个简单的在线商店。一切都很好:我可以将填写表格的客户的姓名、地址、电话和电子邮件保存到 Mongo,但问题是如果有 2 个或更多不同的产品,我无法保存正确的产品数据。 Mongo 只接收最后一个产品的数据,如下图所示。以下是我的部分代码:

// My Order's schema
var orderSchema = Schema({
    name: {
        type: String,
        required: true
    },
    address: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        required: true
    },
    email: {
        type: String,
    },
    product: [{
        image: String,
        title: String, 
        price: Number,
        qty: Number,
    }],
    /* subtotal: {
        type: Number,
        required: true
    },
    total: {
        type: Number,
        required: true
    } */
});

var Order = module.exports = mongoose.model('Order', orderSchema);

// My Product's schema
var productSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    slug: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    category: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    image: {
        type: String,
    },
});

module.exports = mongoose.model('Product', productSchema);

<!-- Form for the customers to fill their information -->
<form action="/orders/confirm" method="POST">
    
        <div class="form-group">
            <label>Name</label>
            <input type="text" class="form-control" name="name" placeholder="Name" required>
        </div>

        <div class="form-group">
            <label>Address</label>
            <input type="text" class="form-control" name="address" placeholder="Address" required>
        </div>
        
        <div class="form-group">
            <label>Phone</label>
            <input type="tel" class="form-control" name="phone" placeholder="Phone number: 0123456789" pattern="[0-9]{10}" required>
        </div>

        <div class="form-group">
            <label>Email</label>
            <input type="text" class="form-control" name="email" placeholder="Email">
        </div>

        <div class="form-group">
            <label>Product</label>
            <div class="col-xs-12 col-md-5">
                <table class="table table-stripped align-mid">
                    <tr>
                        <th>Image</th>
                        <th>Product</th>
                        <th>Price</th>
                        <th>Quantity</th>
                        <th></th>
                        <th>Subtotal</th>
                    </tr>
        
                    <% var total = 0; %>
                    <% cart.forEach((product) => { %>
                        <% var sub = product.qty * product.price; %>
                        <% total += +sub; %>
                        <tr>
                            <td><img class="cpi" src="<%= product.image %>" alt="<%= product.slug %>"></td>
                            <td><%= product.title %></td>
                            <td><%= product.price %> VND</td>
                            <td><%= product.qty %></td>
                            <td></td>
                            <td><%= sub %> VND</td>
                        </tr>
                    <% }); %>
                    <tr>
                        <td colspan="5" align="right"><b>Total: </b><%= total %> VND</td>
                    </tr>
                </table>
            </div>
        </div>

        <button type="submit" class="btn btn-primary">Confirm Order</button>
        
    </form>

// Routing
router.post('/confirm', (req,res) => {

    var name = req.body.name;
    var address = req.body.address;
    var phone = req.body.phone;
    var email = req.body.email;
    var cartData = req.session.cart;

    req.checkBody('name', 'Name is required!').notEmpty();
    req.checkBody('address', 'Address is required!').notEmpty();
    req.checkBody('phone', 'Phone number is required!').notEmpty();
  
    var errors = req.validationErrors();

    if (errors) {
        res.render('order_info', {
            errors: errors,
            cart: cartData
        });
    } else {
        Order.findOne((err,order) => {
            if (err) {
                res.render('order_info', {
                    errors: errors,
                    cart: cartData
                });
            } else {
                var total = 0;
                cartData.forEach((product) => {
                    var sub = product.qty * product.price;
                    total += +sub;

                    order = new Order({
                        name: name,
                        address: address,
                        phone: phone,
                        email: email,
                        product: [{
                            image: product.image,
                            title: product.title,
                            price: product.price,
                            qty: product.qty,
                            subtotal: sub,
                        }],
                        total: total
                    });
                });

                order.save((err) => {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(order);
                        req.flash('success','Order Confirmed.');
                        cartData.length = 0;
                        res.redirect('/products/all')
                    }
                });
            }

        });
    }
});

(我添加了2个产品到购物车,第一个产品的价格是5000000,第二个是3500000)

我尝试了很多方法,但没有任何效果。请帮忙!提前谢谢你。

【问题讨论】:

    标签: javascript node.js mongodb express mongoose-schema


    【解决方案1】:

    // Your schema should be
    var productSchema = mongoose.Schema({
        title: {
            type: String,
            required: true
        },
        slug: {
            type: String,
            required: true
        },
        description: {
            type: String,
            required: true
        },
        category: {
            type: String,
            required: true
        },
        price: {
            type: Number,
            required: true
        },
        image: {
            type: String,
        },
    });
    
    module.exports = mongoose.model('Product', productSchema);

    【讨论】:

    • 谢谢。问题解决了,但又出现了一个新问题。如果有 2 个或更多产品,我无法保存正确的数据。你能告诉我我的代码有什么问题吗?
    • 看来cartData.forEach((product) =&gt; { 您正在为购物车中的每件商品创建一个新订单。您应该对其进行重构以计算小计和总计,然后将订单与最终数据一起保存,因此您将在循环外创建一个新订单
    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2018-06-02
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    相关资源
    最近更新 更多