I'm currently learning how to build full stack JavaScript applications using the MEAN stack, which includes Node.js, AngularJS, Express and MongoDB.
At this stage of my studies, I am tasked with fetching all the hotel data from my database.
However, when I enter http: // localhost: 3000 / api / hotels / in my browser, the database returns an empty array even though the hotel.data.json file is populated.
I attempted to replicate a section5 teacher's final project code, but unfortunately encountered the same issue - my database remains empty [].
This is the snippet from the hotels.controllers file:
var mongoose = require('mongoose');
var Hotel = mongoose.model('Hotel');
module.exports.hotelsGetAll = function(req, res) {
console.log('GET the hotels');
console.log(req.query);
var offset = 0;
var count = 5;
if (req.query && req.query.offset) {
offset = parseInt(req.query.offset, 10);
}
if (req.query && req.query.count) {
count = parseInt(req.query.count, 10);
}
Hotel
.find()
.skip(offset)
.limit(count)
.exec(function(err, hotels) {
console.log("Found hotels", hotels.length);
res
.json(hotels);
});
};
module.exports.hotelsGetOne = function(req, res) {
var id = req.params.hotelId;
console.log('GET hotelId', id);
Hotel
.findById(id)
.exec(function(err, doc) {
res
.status(200)
.json(doc);
});
};
module.exports.hotelsAddOne = function(req, res) {
console.log("POST new hotel");
var db = dbconn.get();
var collection = db.collection('hotels');
var newHotel;
if (req.body && req.body.name && req.body.stars) {
newHotel = req.body;
newHotel.stars = parseInt(req.body.stars, 10);
collection.insertOne(newHotel, function(err, response) {
console.log("Hotel added", response);
console.log("Hotel added", response.ops);
res
.status(201)
.json(response.ops);
});
} else {
console.log("Data missing from body");
res
.status(400)
.json({
message: "Required data missing from body"
});
}
};