2017-02-15 5 views
0

ブラウザでjsonデータを表示しようとすると、完全なデータではなく[]が表示されます。 mongooseを使ってmongodbからデータを表示しようとしています。データベースに1つのコレクションがあり、表示しようとしているドキュメントが1つしかありませんが、私は[]を取得します。どうして? 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シェルでは、すべてうまく動作し、エラーはありません。 – Uros

+0

あなたのコードをコピーしたところ、エラーが見つかりました。モデル宣言から 'new'を削除してください。 –

+0

まだ動作しません。私は[]を得るだけです。 _new_を考慮すると、それはエラーではありません[リンク](http://mongoosejs.com/docs/guide.html)。私はmongoを再起動し、コードのすべての組み合わせを試し、mongoシェルでチェックし、まだ私はjsonデータを取得しません。 – Uros

関連する問題