Reputation: 1834
I would like to pass the JSON object along with the view when I show a model Object in Node/Express using Mongo.
Curren route (passing just the view):
app.get('/page/:customurl', function(req, res, next) {
Page.findOne({ customurl: req.params.customurl.toLowerCase()}, function(error, page) {
if (!page) return next(new NotFound('Document not found'));
res.render('pages/page_show.ejs',
{ locals: {
title: 'ClrTouch | ' + page.title,
page:page,
}
});
});
});
Can I add pagejson:page.toObject()
to the locals and then put pagejson
on my page somewhere? When I tried that it showed up as [object, Object] at the browser. Is there any easy way to pass the JSON to the view?
Thanks!
Upvotes: 1
Views: 7541
Reputation: 1141
You should look at JSON methods
In node repl:
> var document = {a: 'first property', b: 'second property'};
> JSON.stringify(document)
'{"a":"first property","b":"second property"}'
>
If you need to respond to the route in different ways (ex. requested via ajax) you can either pass a new parameter to the url app.get('/page/:customurl.:format', ...
or checking the request headers stored in req.headers
if ( req.headers["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest" ) {
res.send(document);
} else {
res.render(...);
}
Upvotes: 6