如何将mongodb数据显示为JSON? (的NodeJS)

时间:2015-09-01 15:08:29

标签: json node.js mongodb

所以我要问的是如何在单独的页面上将我的MongoDB数据显示为JSON?到目前为止,我有一个名为“电影”的数据库,它有一个包含一堆电影片名,评级和股票的表格。

如下所示:

{ "_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 }

我还有我希望json显示在的页面:

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;

架构:

var movieSchema = new Schema({
  movieTitle: {
    type: String,
    required: true
  },
  rating: {
    type: String
  },
  stock: {
    type: String,
    required: true
  },
  sort: {
    type: String
  }
});

有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

我认为你可以这样做:

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;

答案 1 :(得分:0)

对于那些想要了解我是如何工作的人

/* 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);
    });
});