Reputation: 311
So what I'm asking is how I would show my MongoDB data as JSON on a seprate page? So far I have a database called 'movies' which has a table that contains a bunch of movie titles, rating and stock.
As seen here:
{ "_id" : ObjectId("55e579d30bb58af007d4d8f3"), "movieTitle" : "Iron Man", "rating" : "Excellent", "stock" : "Yes", "sort" : "iron man", "__v" : 0 }
{ "_id" : ObjectId("55e59c3d1d19a3d20ae67a9c"), "movieTitle" : "A Bittersweet Life", "rating" : "Poor", "stock" : "Yes", "sort" : "a bittersweet life", "__v" : 0 }
{ "_id" : ObjectId("55e59c441d19a3d20ae67a9d"), "movieTitle" : "A Team", "rating" : "Okay", "stock" : "No", "sort" : "a team", "__v" : 0 }
I also have the page I want the json to be displayed on:
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('data', {});
});
module.exports = router;
Schema:
var movieSchema = new Schema({
movieTitle: {
type: String,
required: true
},
rating: {
type: String
},
stock: {
type: String,
required: true
},
sort: {
type: String
}
});
Can someone help me out?
Upvotes: 0
Views: 529
Reputation: 311
For those who want to see how I got it working:
/* GET home page. */
router.get('/', function(req, res, next) {
// Get Movie schema for use
var Movie = mongoose.model('movie');
// Query all records using aggregate
Movie
.aggregate()
.match({})
.sort({ sort: 1 })
.exec(function(err, movies) {
// Handle errors
if (err) {
return res
.status(500)
.json({
error: err
});
}
// Manipulate movies to tidy up keys
movies.forEach(function (movie) {
movie.id = movie._id;
delete movie._id;
delete movie.__v;
delete movie.sort;
});
return res.json(movies);
});
});
Upvotes: 0
Reputation: 512
I think you could do something like this:
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
var movieSchema = new Schema({
movieTitle: {
type: String,
required: true
},
rating: {
type: String
},
stock: {
type: String,
required: true
},
sort: {
type: String
}
});
var Movie = mongoose.model('Movie', movieSchema, 'movies');
mongoose.connect('localhost', function(err, res){
})
/* GET home page. */
router.get('/', function(req, res, next) {
Movie.find({}, function(err, movies) {
res.render('data', movies);
})
});
module.exports = router;
Upvotes: 1