Node JS express - 更新单个文档

时间:2016-12-13 23:21:15

标签: javascript node.js express ejs

我无法弄清楚为什么我的文档没有更新。

我获取任何记录并将其加载到http://localhost:3000/update2?buyerID=2299的表单中。但是,当我更改字段并单击“提交”时,当我重定向到列出所有文档的路径时,该字段不会更新。它和以前一样。

任何人都可以看到我出错的地方吗?

http://prntscr.com/dj49wd - 表格

获取

router.get('/update2', function(req, res) {
        var buyerID = req.query.buyerID;

        if (!buyerID || !parseInt(buyerID)) {
            res.render('error', {message: "You need to enter a buyerID to update a specific order", error:{status:"", stack: ""}});
        } else {

            mongoClient.connect(url, function (err, db) {
                if (err) {
                    res.render('error', {message: "Failed to connect to MongoDB",error:{status:"", stack: ""}});
                } else {
                    var WishList = db.collection('orders');
                    WishList.findOne({"buyerID": parseInt(buyerID)}, function(err, result) {
                        if (err || !result || result.length == 0) {
                            res.render('error', {message: "Failed to find order",error:{status:"", stack: ""}});
                        } else {
                            console.log("get results", result)
                            res.render('updateOrder2', {qs: result});
                        }
                    })
                }
            });
        }
    });

发表

    router.post('/update2', function(req, res) {
        if (!buyerID || !parseInt(buyerID)) {
            res.render('error', {message: "Failed to update order make sure the ID is current", error:{status:"", stack: ""}});
        } else {

            mongoClient.connect(url, function (err, db) {
                if (err) {
                    res.render('error', {message: "Failed to connect to MongoDB", error:{status:"", stack: ""}});
                } else {
                    var WishList = db.collection('orders');
                    var buyerID = req.query.buyerID;

                    var u2Order = {
                        buyerID: req.body.buyerID,
                        name: {
                            f: req.body.f,
                            s: req.body.s
                        },
                        address: {
                            HouseNum: req.body.HouseNum,
                            streetName:req.body.streetName,
                            town:req.body.town,
                            postCode: req.body.postCode
                        },
                        deliveryInfo: [{delivId: req.body.delivId,
                            serviceName: req.body.serviceName,
                            postTime: req.body.postTime,
                            delivCost: req.body.delivCost,
                            pickUp: req.body.pickUp}],

                        gender: req.body.gender,
                        student: req.body.student,
                        pName: req.body.pName,
                        purchaseDate: req.body.purchaseDate,
                        price: req.body.price,
                        sName: req.body.sName

                    };
                    console.log("Updating..", u2Order)
                    WishList.updateOne({"buyerID": parseInt(buyerID)}, {$set: u2Order}, function (err, result){
                        if (err) {
                            console.log("Cannot update", err)
                        } else {
                            console.log("Updated..", order)
                            res.redirect("/orders")
                        }
                    })

                }
            });
        }
    });

JSON

{  
      "buyerID":2447,
      "name":{  
         "f":"Jess",
         "s":"Thompson"
      },
      "gender":"Female",
      "birthDate":"1987-02-02",
      "student":false,
      "appOS":"Android",
      "address":{  
         "HouseNum":"22",
         "streetName":"Coolford Road",
         "town":"Sedley",
         "postCode":"DY3 9CK"
      },
      "productID":2382,
      "pName":"Macbook Pro",
      "type":"Laptop",
      "purchaseDate" : "2016-11-30", 
      "releaseDate":"2016-03-11",
      "provider":"Apple",
      "starRating":3,
      "available":true,
      "About":"2.9GHz dual-core Intel Core i5 processor, Turbo Boost up to 3.3GHz",
      "sellerID":2245,
      "sName":"Amazon.co.uk",
      "price":1700.33,
      "discount":false,
      "deliveryInfo":[  
         {  
            "delivId":2382,
            "serviceName":"UPS",
            "postTime":"1 Day",
            "delivCost":"£7.50",
        "pickUp": false
         },
         {  
            "delivId":2383,
            "serviceName":"Royal Mail",
            "postTime":"2-5 Days",
            "delivCost":"free",
            "pickUp": false
         },
         {  
            "delivId":2384,
            "serviceName":"UPS",
            "postTime":"1 Week",
            "delivCost":"free",
            "pickUp": true

         }
      ]
   }

updateOrder2.ejs

<!DOCTYPE html>
<html>
<head>
    <title>Update Recipe</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>

<form name= "updateOrder" action="/updateOrder" method="POST">
    User ID:<br>
    <input type="text" name="buyerID" value = "<%=qs.buyerID%>"><br>
    <b><p>Nested Objects (firstname and second name)</p></b>
    First Name:<br>
    <input type="text" name="f" value = "<%=qs.name.f%>"/><br>
    Second Name:<br>
    <input type="text" name="s" value = "<%=qs.name.s%>"/><br>
    <b><p>Nested object - customer address</p></b>
    House number:<br>
    <input type="text" name="HouseNum" value = "<%=qs.address.HouseNum%>"/><br>
    Street name:<br>
    <input type="text" name="streetName" value = "<%=qs.address.streetName%>"/><br>
    town:<br>
    <input type="text" name="town" value = "<%=qs.address.town%>"/><br>
    post code:<br>
    <input type="text" name="postCode" value = "<%=qs.address.postCode%>"/><br>
    Gender:<br>
    <input type="text" name="gender" value = "<%=qs.gender%>"/><br>
    Student?:<br>
    <input type="text" name="student" value = "<%=qs.student%>"/><br>
    Product ID:<br>
    <input type="text" name="productID" value = "<%=qs.productID%>"/><br>
    Product Name:<br>
    <input type="text" name="pName" value = "<%=qs.pName%>"/><br>
    Product Type:<br>
    <input type="text" name="type" value = "<%=qs.type%>"/><br>
    Date Purchased:<br>
    <input type="text" name="purchaseDate" value = "<%=qs.purchaseDate%>"/><br>
    Product Price:<br>
    <input type="text" name="price" value = "<%=qs.price%>"/><br>
    Seller Name:<br>
    <input type="text" name="sName" value = "<%=qs.sName%>"/><br>
    <b><p>Array Objects (delivery details)</p></b>
    DeliveryID:<br>
    <input type="text" name="delivID" value = "<%=qs.deliveryInfo[1].delivId%>"/><br>
    Survice Name:<br>
    <input type="text" name="serviceName" value = "<%=qs.deliveryInfo[1].serviceName%>"/><br>
    Post Time:<br>
    <input type="text" name="postTime" value = "<%=qs.deliveryInfo[1].postTime%>"/><br>
    Delivery cost:<br>
    <input type="text" name="delivCost" value = "<%=qs.deliveryInfo[1].delivCost%>"/><br>
    Pickup:<br>
    <input type="text" name="pickUp" value = "<%=qs.deliveryInfo[1].pickUp%>"/><br>
    <br><br>
    <input type="submit" value="Submit" />
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您是否尝试findOne然后使用markModified对象字段进行修改?

function async(cb) {
    WishList.findOne({id: id}, function(err, doc) {
      if (err) throw err;
        doc.buyerID = req.body.buyerID;
        doc.name = {
            f: req.body.f,
            s: req.body.s
        };
        doc.address = {
            HouseNum: req.body.HouseNum,
            streetName:req.body.streetName,
            town:req.body.town,
            postCode: req.body.postCode
        };
        doc.deliveryInfo = [{delivId: req.body.delivId,
            serviceName: req.body.serviceName,
            postTime: req.body.postTime,
            delivCost: req.body.delivCost,
            pickUp: req.body.pickUp}];

        doc.gender = req.body.gender,
        doc.student = req.body.student,
        doc.pName = req.body.pName,
        doc.purchaseDate = req.body.purchaseDate,
        doc.price = req.body.price,
        doc.sName = req.body.sName

        doc.markModified('name');
        doc.markModified('address');
        doc.markModified('deliveryInfo');

        doc.save(cb);

      };
}

答案 1 :(得分:0)

这是正确的吗?

router.get('/update2', function (req, res) {
    var buyerID = req.query.buyerID;

    if (!buyerID || !parseInt(buyerID)) {
        res.render('error', {
            message: "You need to enter a buyerID to update a specific order",
            error: {status: "", stack: ""}
        });
    } else {
        var MongoClient = mongodb.MongoClient;
        MongoClient.connect(url, function (err, db) {
            if (err) {
                res.render('error', {message: "Failed to connect to MongoDB", error: {status: "", stack: ""}});
            } else {
                function async(cb) {
                    var WishList = db.collection('orders');
                    WishList.findOne({"buyerID": parseInt(buyerID)}, function (err, result) {
                        if (err || !result || result.length == 0) {
                            res.render('error', {message: "Failed to find order", error: {status: "", stack: ""}});
                        } else {
                            doc.buyerID = req.body.buyerID;
                            doc.name = {
                                f: req.body.f,
                                s: req.body.s
                            };
                            doc.address = {
                                HouseNum: req.body.HouseNum,
                                streetName: req.body.streetName,
                                town: req.body.town,
                                postCode: req.body.postCode
                            };
                            doc.deliveryInfo = [{
                                delivId: req.body.delivId,
                                serviceName: req.body.serviceName,
                                postTime: req.body.postTime,
                                delivCost: req.body.delivCost,
                                pickUp: req.body.pickUp
                            }];

                            doc.gender = req.body.gender,
                                doc.student = req.body.student,
                                doc.pName = req.body.pName,
                                doc.purchaseDate = req.body.purchaseDate,
                                doc.price = req.body.price,
                                doc.sName = req.body.sName

                            doc.markModified('name');
                            doc.markModified('address');
                            doc.markModified('deliveryInfo');

                            doc.save(cb);
                            console.log("get results", result)
                            res.render('updateOrder2', {qs: result});

                        }
                    })
                }
            }
        })
    }
})











router.post('/update2', function (req, res) {
    if (!buyerID || !parseInt(buyerID)) {
        res.render('error', {
            message: "Failed to update order make sure the ID is current",
            error: {status: "", stack: ""}
        });
    } else {
        var MongoClient = mongodb.MongoClient;
        MongoClient.connect(url, function (err, db) {
            if (err) {
                res.render('error', {message: "Failed to connect to MongoDB", error: {status: "", stack: ""}});
            } else {
                var WishList = db.collection('orders');
                var buyerID = req.query.buyerID;

                var u2Order = {
                    buyerID: req.body.buyerID,
                    name: {
                        f: req.body.f,
                        s: req.body.s
                    },
                    address: {
                        HouseNum: req.body.HouseNum,
                        streetName: req.body.streetName,
                        town: req.body.town,
                        postCode: req.body.postCode
                    },
                    deliveryInfo: [{
                        delivId: req.body.delivId,
                        serviceName: req.body.serviceName,
                        postTime: req.body.postTime,
                        delivCost: req.body.delivCost,
                        pickUp: req.body.pickUp
                    }],

                    gender: req.body.gender,
                    student: req.body.student,
                    pName: req.body.pName,
                    purchaseDate: req.body.purchaseDate,
                    price: req.body.price,
                    sName: req.body.sName

                };
                console.log("Updating..", u2Order)
                WishList.updateOne({"buyerID": parseInt(buyerID)}, {$set: u2Order}, function (err, result) {
                    if (err) {
                        console.log("Cannot update", err)
                    } else {
                        console.log("Updated..", order)
                        res.redirect("/orders")
                    }
                })
                db.close();
            }
        })
    }
})