连接到 mongodb

Connecting to the mongodb

我是 MEAN 开发的新手,我正在开发一个简单的应用程序,第一步是尝试连接到我的 mongodb,所以我安装了 node、express、morgan, mongodb,猫鼬。

所以这是我在 index.js 中的代码:

const express = require('express');
const morgan = require('morgan');
const app = express();

const { MongoClient } = require('./database');

// Settings
app.set('port', process.env.PORT || 3000);


// Middlewares
app.use(morgan('dev'));
app.use(express.json());

// Routes


// Starting the server
app.listen(app.get('port'), () => {
    console.log('server on port', app.get('port'));
});

然后是我的代码 database.js:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>@cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  console.log("horrorrrrrr");
  // perform actions on the collection object
  client.close();
}); 

module.exports = MongoClient;

我也尝试使用 mongodb 页面上的代码连接到应用程序:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>@cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

当然是把密码改成真密码了。请记住我的今天这是我第一次接触 mongodb 也是 MEAN 全栈,我在这个连接上花费了太多时间。

这是我得到的错误:

(node:5284) 弃用警告:当前的服务器发现和监控引擎已弃用,并将在未来版本中删除。要使用新的 Server Discover 和 Monitoring 引擎,请将选项 { useUnifiedTopology: true } 传递给 MongoClient 构造函数。

编辑

@iLiA 感谢您的回复!我试过你的代码但没有用,我会告诉你我是如何用真实密码做到的:

const url = 'mongodb+srv://duke:password@cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority';

const mongoose = require('mongoose');
mongoose.connect(url, {
   useNewUrlParser: true,
   useCreateIndex: true,
   useUnifiedTopology: true,
   useFindAndModify: false
})
.then(()=>{
    console.log('congrats, problem solved')
})
.catch((err)=>{
    console.log(`there is not a problem with ${err.message}`);
    process.exit(-1)
})



module.exports = mongoose;

错误是: Server selection timed out after 30000 ms 没有问题 [nodemon] 应用程序崩溃 - 在启动之前等待文件更改...

亲切的问候,

我很困惑你为什么要同时下载 mongodbmongoose 但这是 mongoose 解决方案

const mongoose = require('mongoose');
mongoose.connect(url, {
   useNewUrlParser: true,
   useCreateIndex: true,
   useUnifiedTopology: true,
   useFindAndModify: false
})
.then(()=>{
    console.log('congrats, problem solved')
})
.catch((err)=>{
    console.log(`there is a problem with ${err.message}`);
    process.exit(-1)
})

编辑: 因为你似乎忘记了在 mongo atlas 中将你的 IP 地址列入白名单。