【发布时间】: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