Just starting with mongoDB and mongoose, I have a database called "Twitter" with a collection called userPost. I have my server.js with the connection to the database and the server setup. And the pages.js file in the router folder, which routes every page.
I want the db data to be displayed into a div called "Test".
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. But I'm having some problem in doing that so a helpfull hand would be appreciated. Thanks!
I've created a model schema:
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.
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***
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>
<head>
</head>
<body>
<div>
<h1><%userDetails.username%></h1>
</div>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.