To install the mongoose:
1
|
npm install mongoose
|
routes/post.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var express = require('express');
var router = express.Router();
var Post = require('../schema/post');
/* GET post page. */
router.get('/', function(req, res, next) {
Post.find({}, function(err, posts) {
if (err) {
console.log(err);
} else {
res.render('post', { title: 'Post', posts: posts });
}
});
});
module.exports = router;
|
MongoDB connection using mongoose with node JS:
Write the following code in app.js
1
2
3
4
5
6
7
|
// DB connection
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_database')
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
// DB connection end
|
Create schema for blog post:
schema/post.js
1
2
3
4
5
6
7
8
9
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var BlogPost = new Schema({
name :String,
email :String,
message :String
});
module.exports = mongoose.model('Post', BlogPost);
|
View :
views/post.ejs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<table class="table table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Message</th>
<th>Action</th>
</tr>
</thead>
<%
if (typeof posts != 'undefined' && posts) {
posts.forEach( function ( post ){ %>
<tr>
<td><%= post.name %></td>
<td><%= post.email %></td>
<td><%= post.message %></td>
<td>
<a href="/post/edit/<%= post._id %>" title="Edit Post">Edit</a>
<a href="/post/destroy/<%= post._id %>" title="Delete Post">Delete</a>
</td>
</tr>
<% });
}
%>
</table>
|