如何使用 find() 函数从 MongoDB 调用数据?

How to call data from MongoDB with find() function?

我从 Node.js/MongoDB 开始,我正在努力从数据库中获取数据。

没有任何控制台错误,所以我不确定这有什么问题。我怀疑我在 api.js

中对 find() 做错了什么

这是Team.json。通常,这里是已经导入 MongoDB

的数据
{"Teams": [
{"name": "Real Madrid", "City": "Madrid", "conference":"rmd"},
{"name": "Liverpool", "City": "Liverpool", "conference":"liv"},
{"name": "Bayern Munich", "City": "Munich", "conference":"mun"} ]}

这是 api.js 我创建 GET 请求的地方

const express = require('express')
var router = express.Router({mergeParams: true});
const Team = require('../models/Team')

router.get('/team', (req, res) => {

    Team.find(null)
    .then(data => {
        res.json({
            confirmation: 'success',
            data: data
        })
    })
    .catch(err => {
        res.json({
            confirmation: 'fail',
            message: err.message
        })
    })

})

module.exports = router;

这是 app.js,我在这里创建了 Express 应用程序并调用了 API

let express = require('express')

const config = {
    views: 'views',
    static: 'public',
    db: {
    url: 'mongodb://localhost/footballdb',
    type: 'mongo', 
    onError: (err) => {
        console.log('DB connection failed')
     },
     onSuccess: () => {
         console.log('DB connected')
     }

    }
}

let app = express(config)
const api = require('./routes/api')
app.use('/api', api )


app.listen(4005, () => {
    console.log('Example app is listening on port 4005!')
})



module.exports = app;

编辑:

也许这也会有所帮助: model/Team.js

const mongoose = require('mongoose')

const Team = new mongoose.Schema({
 name:{type: String, default: ''},
 City:{type: String, default: ''},
 conference: {type: String, default:''}
})


module.exports = mongoose.model('Team',Team)

我希望在 http://localhost:4005/api/team but the only thing that I can see is this: http://prntscr.com/pkkgmt

下的浏览器中看到来自 JSON 文件的数据

我的 MongoDB 在本地是 运行,我不知道我做错了什么?

不如发个空的object找

你能试试下面的代码并说说会发生什么吗?

const express = require('express')
var router = express.Router({mergeParams: true});
const Team = require('../models/Team')

router.get('/team', (req, res) => {

    Team.find({})
    .then(data => {
      console.log(data);

        res.json({
            confirmation: 'success',
            data: data
        })
    })
    .catch(err => {
      console.log(err);
        res.json({
            confirmation: 'fail',
            message: err.message
        })
    })

})

module.exports = router;

还向团队 collection 导入的文档与团队架构的形状不匹配。在您的 collection 个团队中有 parent 个团队 属性。

Collections 必须采用以下格式:

https://prnt.sc/pkp9bt

示例数据:

{
    "_id" : ObjectId("5da8a15fc0f0eb20a0e425d6"),
    "name" : "Bayern Munich",
    "City" : "Munich",
    "conference" : "mun"
}

{
    "_id" : ObjectId("5da8a12dc0f0eb20a0e425d5"),
    "name" : "Liverpool",
    "City" : "Liverpool",
    "conference" : "liv"
}

{
    "_id" : ObjectId("5da8a108c0f0eb20a0e425d4"),
    "name" : "Real Madrid",
    "City" : "Madrid",
    "conference" : "rmd"
}