【发布时间】:2018-01-16 04:22:54
【问题描述】:
我正在研究使用 Node.js、AngularJS、Express 和 MongoDB 使用 MEAN 堆栈构建全堆栈 JavaScript 应用程序。
我在第三部分,我必须检索数据库中的所有酒店。
当我在浏览器中输入http://localhost:3000/api/hotels/时,我的数据库返回一个空数组,但hotel.data.json文件已满。
我也试了一份section5老师的期末作业,结果还是一样,我的数据库是空的[]。 这是hotels.controllers文件的代码:
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);
});
// console.log(newHotel);
// res
// .status(200)
// .json(newHotel);
} else {
console.log("Data missing from body");
res
.status(400)
.json({
message: "Required data missing from body"
});
}
};
【问题讨论】:
-
你想从哪里提取数据?来自数据库还是来自 json 文件?
-
也发布你的路线,你的 console.log("Found hotels", hotels.length) 显示什么
-
您是从 Mongo 还是从
hotel.data.json获取数据?不清楚
标签: javascript mongodb mongoose database