2017-02-15 15 views
0

因此,當我嘗試在瀏覽器中顯示json數據時,我只獲取[]而不是全部數據。 我試圖用mongoose和express來顯示mongodb的數據。我有一個數據庫集合和一個文件,我試圖顯示,但我只能得到[]。爲什麼?下面是代碼: app.js:爲什麼我只在res.json()的web頁面中獲得[]

const express = require('express'); 
const mongoose = require('mongoose'); 
const bodyParser = require('body-parser'); 
const Person = require('./Person.model'); 

const app = express(); 

mongoose.Promise = global.Promise; 
const db = 'mongodb://localhost/project'; 
mongoose.connect(db); 
mongoose.connection.once('open',() => console.log('connection has been made...')). 
on('error', (error) => console.log(error)); 

app.get('/', function(req, res) { 
    res.send('It is good to be here'); 
}); 

app.get('/persons', function(req, res) { 
    Person.find({}).exec(function(error, persons) { 
     if (error) { 
      res.send(error); 
     } else { 
      res.json(persons); 
     } 
    }); 
}); 

app.listen(3000,() => console.log('now listening to port 3000')); 

和Person.model.js:

const mongoose = require('mongoose'); 

const Schema = mongoose.Schema; 

const PersonSchema = new Schema({ 
    name: String, 
    age: Number, 
    favcolor: String, 
    osobina: String 
}); 

const Person = mongoose.model('person', PersonSchema); 

module.exports = Person; 
+0

你確實有數據在數據庫中,對嗎? –

回答

0

因爲你使用無極與貓鼬,你可以嘗試改變你的代碼,而不是使用回調函數這樣

app.get('/persons', function(req, res) { 
    Person.find({}).exec().then(function(persons) { 
    res.json(person); 
    }).catch(function(error) { 
    res.send(error); //Will lead to a 200 with the error message inside 
    }); 
}); 

編輯

定義模型時不應使用new。我已經從你的模型中刪除了一點冗餘代碼,這是工作:

const mongoose = require('mongoose'); 

const PersonSchema = mongoose.Schema({ 
    name: String, 
    age: Number, 
    favcolor: String, 
    osobina: String 
}); 

module.exports = mongoose.model('person', PersonSchema); 
+0

我仍然只在瀏覽器中獲得[]並且沒有json數據。我嘗試過使用其他數據庫和集合,並且總是得到相同的結果。在mongo shell中,一切正常,沒有錯誤。 – Uros

+0

複製你的代碼並發現錯誤,只需從模型聲明中刪除'new' –

+0

仍然不起作用。我只得到[]。考慮_new_這不是一個錯誤[鏈接](http://mongoosejs.com/docs/guide.html)。我重新啓動了mongo,嘗試了所有代碼組合,在mongo shell中檢查,但仍然沒有收到json數據。 – Uros

相關問題