簡體   English   中英

將Node.js API連接到MongoDB

[英]Connection Node.js API to MongoDB

我正在嘗試在Node.js上構建API-REST。 我之前做了另一個,但是現在我無法連接到MongoDB數據庫。 該數據庫具有身份驗證過程,但是以某種方式,憑據無法正常工作。 我可以使用它們在本地連接到數據庫,但是在嘗試遠程連接時無法連接。

我讀了一會兒,似乎由於一些更新,我嘗試使用的連接字符串根本無法工作。 這是一些代碼:

config.js:

    module.exports = {
port: process.env.PORT || XXXX,
  db: process.env.MONGODB || 'mongodb://user:password@[IP adresss]:[port]/[databaseName]',
  TOKEN_SECRET: process.env.TOKEN_SECRET || 'aSecretToken'
}

index.js:

    'use strict'

const mongoose = require('mongoose')
const app = require('./app')
const config = require ('./config')

mongoose.Promise = global.Promise;
mongoose.connect(config.db, (err,res) => {
  if(err){
    return console.log(`Error when connecting database: ${err}`)
  }
  console.log('Connection to Mongo database successful...')

  app.listen(config.port, () => {
  console.log(`API REST running on [IP Adress]:${config.port}`)
})
})

我知道,像往常一樣,這可能是以前問過的,而且我想那肯定是世界上最簡單的事情,但是我真的很喜歡這個s ***!

預先感謝,伙計們!

編輯:錯誤日志

(node:3169) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
Error when connecting database: MongoError: Authentication failed.
(node:3169) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Authentication failed.
mongoose.connect("mongodb://user:password@[IP adresss]:[port]/[databaseName]",{auth:{authdb:"admin"}}, () => {})

嘗試把那個選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM