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 SINGLE POST BY ID */
router.get('/edit/:id', function(req, res, next) {
Post.findById(req.params.id, function (err, post) {
if (err) {
console.log(err);
} else {
res.render('post', { title: 'Post Details', postDetail: post });
}
});
});
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
26
27
|
<form class="form-horizontal" role="form" style="width: 50%;" method="post" action="">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<% if (typeof postDetail != 'undefined') { %><%= postDetail.name %><% } %>">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" value="<% if (typeof postDetail != 'undefined') { %><%= postDetail.email %><% } %>">
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" name="message"><% if (typeof postDetail != 'undefined') { %><%= postDetail.message %><% } %></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
</form>
|