Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

node.js - 通过邮递员测试时无法通过猫鼬连接到MongoDB(Can't connect to MongoDB via mongoose when testing through postman)

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

(我无法通过Postman连接到mongoDB发出任何请求...)

I'm getting this in my console:

(我在控制台中得到这个:)

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

Here is my app.js:

(这是我的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文件夹结构:)

    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

(还-我正在遵循一个多元化的教程,可能是这些包是旧的,我正在通过package.json查看-但我完全迷失了)

api/user

(api /用户)

    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

(API /交易)



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

(API /索引js)

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

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

       module.exports = router
  ask by Iurii Kogan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error is probably because the route you're trying to access is not defined by you.

(该错误可能是因为您尝试访问的路由未由您定义。)

Please check if you have defined this POST route in your API or not.

(请检查您是否在API中定义了此POST路由。)

http://localhost:8080/api/user/?ObjectId=5a777f0a75f64a1698221d98.

This error can also occur if your route is defined properly but when you execute the code defined in the route, your server crashes due to unhandled error.

(如果正确定义了路由,但是在执行路由中定义的代码时,由于未处理的错误,服务器也会崩溃,也会发生此错误。)

If possible, paste your code from api.js here.

(如果可能,请在此处粘贴api.js的代码。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...