2017-02-12 70 views
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); 
} 

这就是我重新加载时得到的: result after reload 任何帮助都会很棒。

回答

1

Chatbot是你的数据库名称,但在这里 mongoose.connect('mongodb:// localhost/ChatbotService')你使用的是chatbotservice。我想你在这里连接着不同的数据库。