简体   繁体   English

Express, mongoose 将MongoDB的值显示成一个div

[英]Express, mongoose display MongoDB values into a div

Just starting with mongoDB and mongoose, I have a database called "Twitter" with a collection called userPost.从 mongoDB 和 mongoose 开始,我有一个名为“Twitter”的数据库,其中包含一个名为 userPost 的集合。 I have my server.js with the connection to the database and the server setup.我有我的 server.js 连接到数据库和服务器设置。 And the pages.js file in the router folder, which routes every page.以及路由文件夹中的 pages.js 文件,它路由每个页面。

I want the db data to be displayed into a div called "Test".我希望将数据库数据显示到名为“测试”的 div 中。

router.get('/', function(req, res) {
res.render('index.ejs', {
 });
}); 

This is my homepage route code, I know after the { I should put something like id_of_div:database_value.这是我的主页路由代码,我知道在 { 之后我应该放一些类似 id_of_div:database_value 的东西。 But I'm having some problem in doing that so a helpfull hand would be appreciated.但是我在这样做时遇到了一些问题,因此将不胜感激。 Thanks!谢谢!

I've created a model schema:我创建了一个 model 架构:

let mongoose = require('mongoose');
var Schema = mongoose.Schema;

var postSchema = new Schema({
    username: { 
        type: String,
        required: true 
    },
    content: { 
        type: String,
        required: true 
    },
});

let userPost = module.exports = mongoose.model('userPost', postSchema);

But I don't know how to proceed.但我不知道如何进行。

<div id="posts">
</div>

This is my div in the index.ejs file under a form.这是我在 index.ejs 文件中的一个表单下的 div。

All you need to do is import your module Schema in your router module and render it.您需要做的就是在路由器模块中导入模块架构并渲染它。 Your Routes and app module files will look something like this below您的路线和应用程序模块文件将如下所示

***userRoutes.js***

var express = require('express');
var userPostModel = require('./userPostModel');

const userRouter = express.Router();

function router() {
    userRouter.route('/').get((req, res, next) => {
        userPostModel.find({})
            .then(function (userDetails) {
                res.render('index', {
                    userDetails
                });
            }, function (err) {
                next(err);
            });
        next();
    }); 

    return userRouter;
}

module.exports = router;

Following is the sample app.js file以下是示例 app.js 文件

***app.js***

var express = require('express');
var userRoutes = require('./userRoutes');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/user', userRoutes());
app.set('views', './src/views');
app.set('view engine', 'ejs');

app.listen(3000, function() {
    console.log("Listening to port");
})

Following is the way you could use it in html file以下是您可以在 html 文件中使用它的方式

<html>
    <head>
    </head>
    <body>
        <div>
            <h1><%userDetails.username%></h1>
        </div>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM