ブラウザで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;
データベースにデータがありますか? –