Last Updated
Viewed 44 Times
              

I can't connect to mongoDB via Postman to make any requests...

I'm getting this in my console:

    [nodemon] starting `node app.js`
    API Server Listening on port 8080!

Here is my app.js:

```
    const express = require('express')
    const app = express()
    const api = require('./api')
    const morgan = require('morgan') // logger
    const bodyParser = require('body-parser')
    const cors = require('cors')

    app.set('port', (process.env.PORT || 8080))

    app.use(bodyParser.json)    
    app.use(bodyParser.urlencoded({
        extended: false
    }))

    app.use(cors())

    app.use('/api', api)
    app.use(express.static('static'))

    app.use(morgan('dev'))

    app.use(function (req, res) {
        const err = new Error('Not Found')
        err.status = 404
        res.json(err)
    })

    // Add MongoDB connection and mongoose
    const mongoose = require('mongoose')
    mongoose.connect('mongodb://localhost:27017/globomantics', {
        useNewUrlParser: true, //deprecated url parser
        useUnifiedTopology: true
    })

    const db = mongoose.connection
    db.on('error', console.error.bind(console, 'connection error:'))
    db.once('open', function () {
        app.listen(app.get('port'), function () {
            console.log('API Server Listening on port ' + app.get('port') + '!')
        })
    })
```

All I'm getting from postman is:

    There was an error connecting to http://localhost:8080/api/user/?ObjectId=5a777f0a75f64a1698221d98.

Here is the api folder structure:

    API>
       routes>
           User>
           Transaction>
       index.js

ALSO - i'm following a pluralsight tutorial it might be that the packages are old i'm looking through package.json - but i'm comletely lost

api/user

    const User = require('../../models/user')
    module.exports = function (router) {
          router.get('/user/:id', function (req, res) {
            User.findById(req.params.id).exec()
              .then(docs => res.status(200)
                .json(docs))
              .catch(err => res.status(500)
                .json({
                  message: 'Error finding user',
                  error: err
                }))
          })

          router.get('/user/email/:email', function (req, res) {
            User.find({ 'email': req.params.email }).exec()
              .then(docs => res.status(200)
                .json(docs))
              .catch(err => res.status(500)
                .json({
                  message: 'Error finding user',
                  error: err
                }))
          })

          router.post('/user', function (req, res) {
            let user = new User(req.body)
            user.save(function (err, user) {
              if (err) return console.log(err)
              res.status(200).json(user)
            })
          })

          router.put('/user/:id', function (req, res) {
            console.log(req.body)
            let qry = { _id: req.params.id }
            let doc = {
              // first: req.body.firstName,
              // last: req.body.lastName,
              // email: req.body.email,
              // password: req.body.password,
              isActive: req.body.isActive
            }
            console.log(doc)
            User.update(qry, doc, function (err, respRaw) {
              if (err) return console.log(err)
              res.status(200).json(respRaw)
            })
          })
        }

API/transaction



const Transaction = require('../../models/transaction')
    const mongoose = require('mongoose')

    module.exports = function (router) {
      // Get transactions for given year and month, by userId...
      router.get('/transaction/:year/:month', function (req, res) {
        const userId = req.get('userId')
        const month = req.params.month - 1 // JS months are zero-based
        const year = req.params.year
        const startDt = new Date(Date.UTC(year, month, 1, 0, 0, 0))
        const endDt = new Date(Date.UTC(year, month + 1, 1, 0, 0, 0))

        const qry = {
          userId: userId,
          transactionDate: {
            $gte: startDt,
            $lt: endDt
          }
        }

        Transaction.find(qry)
          .sort({ 'transactionDate': 1 })
          .exec()
          .then(docs => res.status(200)
            .json(docs))
          .catch(err => res.status(500)
            .json({
              message: 'Error finding transactions for user',
              error: err
            }))
      })    


      // Get transactions running balance for a specific user...
      router.get('/transaction/balance/:year/:month', function (req, res) {
        const userId = req.get('userId')
        const month = req.params.month - 1 // JS months are zero-based
        const year = req.params.year
        const endDt = new Date(Date.UTC(year, month, 1))
        const pipeline = [
          {
            $match: {
              userId: mongoose.Types.ObjectId(userId),
            }
          },
          {
            $match: {
              transactionDate: { $lt: endDt }
            }
          },
          {
            $group: {
              _id: null,
              charges: { $sum: '$charge' },
              deposits: { $sum: '$deposit' }
            }
          }
        ]

        Transaction.aggregate(pipeline).exec()
          .then(docs => res.status(200)
            .json(docs))
          .catch(err => res.status(500)
            .json({
              message: 'Error finding transactions for user',
              error: err
            }))
      })

      // Create new transaction document
      router.post('/transaction', function (req, res) {
        let transaction = new Transaction(req.body)
        transaction.save(function (err, transaction) {
          if (err) return console.log(err)
          res.status(200).json(transaction)
        })
      })
    }

API/indexjs

       const express = require('express')
       const router = express.Router()

       require('./routes/transaction')(router)
       require('./routes/user')(router)

       module.exports = router

The question is pretty much self explanatory. I have created a backend for MongoDB using nodeJS. Here is the link to my entire backend project so you can replicate at your own end -->

https://onedrive.live.com/?cid=90b44987ff0f70ac&id=90B44987FF0F70AC%21157&authkey=!AOG8D2nRT--ga9I

Now, through Postman I am trying to send requests to the add operation to add new player items - The steps I am following are -->

  1. starting up mongo.exe and running use playerDB
  2. starting up mongod.exe
  3. opening command terminal on my backend project and running nodemon server
  4. sending a POST request to Mongoose db through postman like localhost:4000/playerDB/add

The error I am receiving is -> 400 Unable to add player object

My sample request body is like so:

{
    "player_name":"Didier Drogba",
    "player_description":"Brawny, cunning, determined and a heart for attempting the most impossible audacious! The one and only!",
    "player_position":"Striker",
    "player_age":"42",
    "player_club":"Chelsea FC",
    "player_":"Hall of Fame",
    "player_isactive":"False",
    "player_completed":"True"
}

What error did I make? What was the problem? Anythign wrong with the sequence of steps I followed? Can you point out where I went wrong?

Thanks,

EDIT--> The new error is:

<body>
        <pre>SyntaxError: Unexpected token F in JSON at position 288
            <br> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)
            <br> &nbsp; &nbsp;at parse (E:\REACT\MyProj\backend\node_modules\body-parser\lib\types\json.js:89:19)
            <br> &nbsp; &nbsp;at E:\REACT\MyProj\backend\node_modules\body-parser\lib\read.js:121:18
            <br> &nbsp; &nbsp;at invokeCallback (E:\REACT\MyProj\backend\node_modules\raw-body\index.js:224:16) .....

I am fairly new to node. I created an application based on this github code:

https://github.com/dalenguyen/rest-api-node-typescript

Yesterday, all was well and it ran just fine with the instructions from the readme.

Today, however, entering

npm start dev

results in the following:

enter image description here

It appears to be looking for c:\code\todonode\server.js, but that file doesn't exist and will not exist. server.ts and thus server.js reside one level down in /lib.

This is very mysterious.

Not sure what further information might be needed. Happy to provide anything that might help.

Why am I getting this error and how can I get my simple server back up and running?

ADDED:

Here is my package.json:

    {
  "name": "todonode",
  "version": "1.0.0",
  "description": "A TypeScript-based node REST API",
  "main": "server.js",
  "scripts": {
    "build": "tsc",
    "dev": "ts-node ./lib/server.ts",
    "start": "nodemon ./dist/server.js",
    "prod": "npm run build && npm run start"
  },
  "author": "Nick Hodges",
  "license": "MIT",
  "dependencies": {
    "@types/express": "^4.17.1",
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongoose": "^5.7.0",
    "nodemon": "^1.19.2"
  }
}

Similar Question 3 : nodemon can not find module debug

I am trying to write a basic MEAN stack application using the express generator command. I am able to run npm start and was able to run my app. However, when I run nodemon I am getting the following error.

module.js:340
    throw err;
          ^
Error: Cannot find module 'debug'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/usr/lib/node_modules/nodemon/lib/nodemon.js:1:75)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

I have checked that the node_modules folder does contain the debug module. I am not able to see where I am going wrong. Can you please help?

Similar Question 5 (2 solutions) : MongoDB can't connect to Server

Similar Question 8 (1 solutions) : Nodejs - Mongoose connect to a defined MongoDB

Similar Question 9 (1 solutions) : Can't insert to MongoDB with Node.js and Mongoose

cc