0

How to redirect to the same view (handlebar) after performing remove data operation in mongodb? I'm trying to perform res.render but it says that web site cannot be reached. Thank you for your help.

Controller

var express = require('express');
var router = express.Router();
var passport = require('passport');
var mongoose = require('mongoose');

var Departments = require('../models/department');
var User = require('../models/user');

router.get('/add_department', userAuthenticated, function(req, res, next) {
	Departments.find(function(err, departments) {
		if (err) {
			throw err;
		}
		res.render('add_department', {title:'Add New Department', departments: departments, name: departments.name, id: departments._id})
	})
})
router.delete('/remove_department/:id', function(req, res) {
	Departments.findById(req.params.id).exec(function(err, doc) {
		if (err) {
			res.statusCode = 404;
			throw err;
		} else {
			doc.remove(function(err) {
				if (err) {
					res.statusCode = 404;
					throw err;
				} else {
					res.render('add_department', {title:'Add New Department', departments: departments, name: departments.name, id: departments._id})
				}
			})
		}
	})
	
})

Handlebar

<div class="container">
<h2>Departments List</h2>
<table class="table">
	<thead>
		<tr>
			<th>Name</th>
			<th>Action</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<form method="POST" action="/departments/create_department">
				<td><input class="form-control" type="text" placeholder="Department Name" name="departmentName"></td>
				<td><button class="btn btn-primary" type="sumit">Add Department</button></td>
			</form>
			<td><button class="btn btn-info">Update</button></td>
			<td><button class="btn btn-info">Clear</button></td>
		</tr>
		{{#each departments}}
		<tr>
			<form method="POST" action="/departments/remove_department/{{_id}}?_method=DELETE">
				<td>{{name}}</td>
				<td><button class="btn btn-danger" type="submit">Remove</button></td>
			</form>
			<form method="POST" action="/departments/edit_department">
				<td><button class="btn btn-warning" value={{id}} type="submit">Edit</button></td>
			</form>
		</tr>
		{{/each}}
	</tbody>
</table>

</div>

1 Answer 1

0

Generally, this would be handled by issuing an actual redirect, rather than just rendering the page in question:

res.redirect('/add_department');

Possibly with some additional meta indicating that the deletion was successful.

That said, there's no specific reason why you can't render inside a delete handler, so I would recommend using a debugger and stepping through the code in the handler to figure out why it's erroring.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.