【问题标题】:NodeJS Mongoose insert event to public/index.htmlNodeJS Mongoose 将事件插入到 public/index.html
【发布时间】:2019-10-26 19:36:53
【问题描述】:

我正在学习 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,我可以在其中使用文档对象来填充表格?

【问题讨论】:

  • 我不确定。您的 index.js 无权访问数据库和集合/文档?
  • 不太清楚您的问题,但您可以使用您的猫鼬承诺并返回该事件的数据。需要一些代码来更好地理解您的问题。
  • 我包含了一些代码并改写了我的问题。对缺乏明确性表示歉意。
  • 在您的情况下,您似乎需要发送多个响应,因为尝试使用“socket.io”或“eventsource”

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

这是一个示例,您可以在其中添加新人员,并且 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();

【讨论】:

  • 谢谢斯蒂芬。只是想知道如何读取 index.html 中的响应数据。最终,我坚持的是如何将数据添加到 html 表中。
  • 如果你可以分享前端 JavaScript 和 index.html 文件,我可以指导你。没有那个就很难了
  • 谢谢。我已将 index.html 添加到问题中。
猜你喜欢
  • 1970-01-01
  • 2011-09-09
  • 2012-11-03
  • 2016-03-30
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
相关资源
最近更新 更多