Search code examples
node.jsexpressmongoose-schema

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


I am starting with Node.js/MongoDB and I am struggling with getting data from DB.

There are not any console errors so I am not sure what is wrong with this. I doubt I'm doing something wrong with find() in api.js

This is Team.json. Generally, here is data which is already imported into MongoDB

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

This is api.js where I am creating my GET request

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;

This is app.js, where I created express app and call 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;

EDIT:

Maybe this will be helpful as well: 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)

I am expecting to see data from JSON file in my browser under http://localhost:4005/api/team but the only thing that I can see is this: http://prntscr.com/pkkgmt

My MongoDB is running locally, and I don't have clue what I am doing wrong?


Solution

  • It is better to send an empty object to find.

    Can you try with the following code and say what happens?

    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;
    

    Also imported documents to team collection do not match the shape of team schema. In your collection teams have a parent teams property.

    Collections must be in this format:

    https://prnt.sc/pkp9bt

    Sample Data:

    {
        "_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"
    }