需要Help.Node.Js使用Ajax和MongoDB CRUD工作缓慢

问题描述 投票:0回答:1

当我尝试从我的数据库添加或删除时,页面需要几秒钟才能更新。我使用AJAX,它仍然很慢。我无法弄清楚问题是什么。我是NODE JS的新手我来自MVC NET。谢谢,这是我的代码。

app.js

let express = require('express');
let app = express();
let mongodb=require('./mongodb')
let bodyParser = require('body-parser');
let index=require('./index');
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.listen(8080, function () {
    console.log('Example app listening on port 8080!');
});
app.use('/',index);
app.use('/mongo',mongodb);

mongodb.js

let express = require('express');
let MongoClient = require('mongodb').MongoClient;
let url = "mongodb://localhost:27017/";
let router = express.Router();

let obj = null;
router.get('/', function (req, res) {
    getDfroMongo(res);
});

function getDfroMongo(res) {
    MongoClient.connect(url, function (err, db) {
        if (err) throw err;
        var dbo = db.db("mydb");
        //Sort the result by name:
        var sort = { car: 1 };
        dbo.collection("customers").find().sort(sort).toArray(function (err, result) {
            if (err) throw err;
            obj = result;
            // db.close();
             res.render(__dirname + '/views/mongo', { result: obj });
           
        });
    });
}


router.post('/', function (req, response) {
    switch (req.body.data) {
        case "add":
            let car = req.body.car;
            let model = req.body.model;
            let year = req.body.year;
            let myimg = req.body.img;
            obj = { car: car, model: model, year: year, img: myimg };
            if (car != "" && model != "" && year != "" && myimg != "") {
                console.log(obj);
                MongoClient.connect(url, function (err, db) {
                    if (err) throw err;
                    var dbo = db.db("mydb");
                    var myobj = { Car: car, Model: model, Year: year, img: myimg };
                    dbo.collection("customers").insertOne(myobj, function (err, res) {
                        if (err) throw err;
                        console.log("1 document inserted");
                        // db.close();
                        getDfroMongo(response);
                    });
                });

            }
            else
                console.log('field missed');
            break;
        case "delete":
            let carName = req.body.carName;
            MongoClient.connect(url, function (err, db) {
                if (err) throw err;
                var dbo = db.db("mydb");
                var myquery = { Car: carName };
                dbo.collection("customers").deleteOne(myquery, function (err, obj) {
                    if (err) throw err;
                    console.log("1 document deleted");
                    // db.close();
                    getDfroMongo(response);
                });
            });
            break;
        case "update":
            upcar = req.body.car;
            upmodel = req.body.model;
            upyear = req.body.year;
            upimg = req.body.img;
            upcarName = req.body.carName;
            // obj = { car: upcar, model: upmodel, year: upyear, img: upimg, carName: upcarName };
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                var dbo = db.db("mydb");
                var myquery = { Car: upcarName };
                var newvalues = { $set: { Car: upcar, Model: upmodel,Year:upyear,img:upimg } };
                dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {
                  if (err) throw err;
                  console.log("1 document updated");
                //   db.close();
                getDfroMongo(response);
                });
              });
              
            break;
        default:
            break;
    }

});
module.exports=router;

这是我的观点-mongo.ejs

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="/css/style.css" rel="stylesheet" type="text/css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <%include title%>
</head>

<body>

    <button type="button" name="addDB" id="addDB" onclick="AddDbFunction()">insert</button>
    <input type="text" name="car" id="car" placeholder="car">
    <input type="text" name="model" id="model" placeholder="model">
    <input type="text" name="year" id="year" placeholder="year">
    <input type="text" name="img" id="img" placeholder="img"><br>
    <button type="button" name="update" id="update" onclick="updateFunction()">update</button>
    <button type="button" name="delete" id="delete" id="delete" onclick="deleteFunction()">delete</button>
    <input type="text" name="carName" id="carName" placeholder="carName">

    <script>

        function updateFunction() {
            let car = document.getElementById("car").value;
            let model = document.getElementById("model").value;
            let year = document.getElementById("year").value;
            let img = document.getElementById("img").value;
            let carName = document.getElementById("carName").value;
            let parameters= { data: "update", car: car, model: model, year: year, img: img, carName: carName };
            $.ajax({
                url: '/mongo',
                type: 'POST',
                data: parameters,
                success: function () {
                    location.reload();
                }
            });
        }

        function deleteFunction() {
            let carName = document.getElementById("carName").value;
            // $.post('/', { data: "delete", carName: carName });
            let parameters = { data: "delete", carName: carName };
            $.ajax({
                url: '/mongo',
                type: 'POST',
                data: parameters,
                success: function () {
                    location.reload();
                }
            });
        }


        function AddDbFunction() {
            let car = document.getElementById("car").value;
            let model = document.getElementById("model").value;
            let year = document.getElementById("year").value;
            let img = document.getElementById("img").value;
            // $.post('/', { data: "add", car: car, model: model, year: year, img: img });
            let parameters = { data: "add", car: car, model: model, year: year, img: img }
            $.ajax({
                url: '/mongo',
                type: 'POST',
                data: parameters,
                success: function () { 
                    location.reload();
                }
            });

        }


    </script>
    <table>
        <tr>
            <th>Car</th>
            <th>Model</th>
            <th>Year</th>
            <th>image</th>
            <!-- <th>id</th> -->
        </tr><br>
        <% for(let i=0; i < result.length; i++) { %>
        <tr>
            <td><%= result[i].Car%></td>
            <td><%= result[i].Model%></td>
            <td><%= result[i].Year%></td>
            <!-- <td><%= result[i]._id%></td> -->
            <td> <img src="\images\<%= result[i].img%> " width="80" height="80"></td><br>
        </tr>
        <% } %>

    </table>

</body>

</html>

谢谢这是个好地方!!

node.js ajax mongodb express ejs
1个回答
0
投票

不要为每个请求连接mongo,只需在脚本开头连接一次即可。

© www.soinside.com 2019 - 2024. All rights reserved.