I have a simple NodeJS, Express, Mongoose app to save and retrieve data from MongoDB based on an online tutorial. Problem I am facing is that whenever I try to retrieve any saved record, I only get _id and __v as shown below...all other movie fields are not displayed. Below is the code I am using to save / retrieve data to/from MongoDB can someone please help by tellin me what I am doing wrong here and how to fix it? Thanks
{
"_id": "542819b25550346209c85272",
"__v": 0
}
app.js:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var movies = require('./routes/movies');
var app = express();
var dbName = 'movieDB';
var connectionString = 'mongodb://localhost:27017/' + dbName;
mongoose.connect(connectionString);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use('/api', movies);
module.exports = app;
movie.js
var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var movieSchema = new Schema({
title: String,
releaseYear: String,
director: String,
genre: String
});
module.exports = mongoose.model('Movie', movieSchema);
movies.js
var Movie = require('../models/movie');
var express = require('express');
var router = express.Router();
router.route('/movies').get(function(req, res) {
Movie.find(function(err, movies) {
if (err) {
return res.send(err);
}
res.json(movies);
});
});
router.route('/movies').post(function(req, res) {
var movie = new Movie(req.body);
movie.save(function(err) {
if (err) {
return res.send(err);
}
res.send({ message: 'Movie Added' });
});
});
module.exports = router;
I have tested saving to the DB using Chrome Postman where I have sent the following data as POST > ROW in JSON format to /api/movies:
{"title":"Matrix Reloaded 2", "releaseYear": "2015", "director": "Mike", "genre": "Action"}
db.yourcollection.find()from themongodbconsole, do you get the documents with all the fields you expect? Just to make sure the documents have the fields you want..toString()as a standard prototype method. But the main problem here is that the content of yourreq.bodylikely does not match your defined schema. That is what you need to "log". Then you will see the problem.