0
我是MongoDB/Node.js/express新手。我正在設置一個應用程序,如下所示: https://www.youtube.com/watch?v=eB9Fq9I5ocsMongoDB快速應用顯示空陣列
我在「chatbot」:「countries」和「population」中創建了一個名爲「chatbot」的數據庫和2個集合。
但是,當我嘗試運行應用程序以顯示我在shell中創建的國家/地區時,除了空數組外,我什麼也得不到。
這裏是集 「國家」:
> db.countries.find()
{ "_id" : ObjectId("58a0c3234d9ba38dcbe1769d"), "name" : "Afghanistan" }
{ "_id" : ObjectId("58a0c3844d9ba38dcbe1769e"), "name" : "Andorra" }
這裏是我的應用程序文件: 的package.json文件:
{
"name": "chatbot",
"version": "1.0.0",
"description": "chatbot app",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"express": "*",
"body-parser": "*",
"mongoose": "*"
},
"author": "Chris",
"license": "ISC",
"devDependencies": {
"nodemon": "^1.11.0"
}
}
app.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
Country = require('./models/country.js');
// Connect to Mongoose
mongoose.connect('mongodb://localhost/ChatbotService')
var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Hola');
});
app.get('/api/countries', function(req, res){
Country.getCountries(function(err, countries){
if(err){
throw err;
}
res.json(countries);
});
});
app.listen(8601);
console.log('Running on port 8601...');
國家.js:
var mongoose = require('mongoose');
// Country Schema
var countrySchema = mongoose.Schema({
name:{
type:String,
required: true
},
create_date:{
type: Date,
default: Date.now
}
});
var Country = module.exports = mongoose.model('Country', countrySchema);
// Get Countries
module.exports.getCountries = function(callback, limit){
Country.find(callback).limit(limit);
}