NodeJS猫鼬插入事件到public / index.html

时间:2019-06-12 10:10:46

标签: node.js mongodb mongoose mongodb-query

我正在学习nodejs,我有一个项目,我希望用户发布表单数据,然后填充位于 public / index.html 中的html表。

目前,我正在使用以下代码将提交的数据写入数据库集合:

const mongoose = require('mongoose')
const express = require('express');
const app = express();
const server = app.listen(3000);

app.use(express.json()); // for retrieving form data
app.use(express.static('public'));

mongoose.connect('mongodb://localhost/class', {useNewUrlParser: true})
        .then( () => console.log('Connected to class database'))
        .catch( () => console.error('Connection attempt to class database failed'))
const personSchema = new mongoose.Schema({
    name: String,
    date: {type: Date, default: Date.now}
})
const Person = mongoose.model('Person', personSchema)


app.post('/join_class', (req,res) => {
    res.send('... joining class')
    console.debug(req.body.name)
    // document.getElementById('class_table').insertRow(req.body.name)
    joinClass(req.body)
})

async function joinClass(data){
    console.log(data)
    person = new Person({
        name: data.name
    })
    await person.save();
}

我的问题是我需要相同的数据来填充位于我的 public / index.html 中的HTML表,但是我当然无法访问index.js中的文档对象。 index.html文件如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js'></script>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <!-- <script src="/client.js"></script> -->
        <title>TestING</title>
    </head>
    <body>
        <table id='class_table'>
            <tr><th>Class</th></tr>
            <tr><td>testing</td></tr>
        </table>
    </body>
</html>

那么,如何创建一个mongoDB事件/警报,以便在将发布数据插入数据库时​​,相同的数据可用于index.html,在这里我可以使用文档对象填充表? >

1 个答案:

答案 0 :(得分:0)

在此示例中,您可以添加新的“人员”,并且index.html页面中的列表应在成功插入后更新。

index.js

app.post('/join_class', (req, res) => {
    var person = new Person({
        name: req.body.name
    });
    person.save().then((data) => {
        res.send(data);
    }).catch((err) => {
        res.status(500).send(err);
    });
})

app.get('/class', (req, res) => {
    Person.find({}).then((data) => {
        res.send(data);
    }).catch((err) => {
        res.status(500).send(err);
    });
})

index.html(正文标签内容)

<body>
    <div>
        Name:<br>
        <input type="text" id="name" value="">
        <br>
        <button onclick="addPerson()">Add Person</button>
    </div>
    <br/>
    <b>Person's in List: </b>
    <ul id='class_table'>

    </ul>
    <script src="/client.js"></script>
</body>

client.js

function listPerson() {
    var req = new XMLHttpRequest();
    req.open("GET", '/class');
    req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    req.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var aList = JSON.parse(req.responseText),
                list = document.getElementById("class_table");
            list.innerHTML = "";    
            aList.forEach(e => {
                var item = document.createElement("li");
                item.innerHTML = e.name;
                list.appendChild(item);
            });

        }
    };
    req.send();
}

function addPerson() {
    var req = new XMLHttpRequest();
    req.open("POST", '/join_class');
    req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    req.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) { listPerson(); } //Get list of Person on completion
    };
    var sName = document.getElementById("name").value;
    req.send(JSON.stringify({ "name": sName }));
}

//Initially load a list of Person's
listPerson();