连接到mongodb

问题描述 投票:0回答:1

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

所以这是我在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全栈,而我在连接中花费了太多时间。

亲切的问候,

mongodb express mean-stack
1个回答
0
投票

<password>更改为您的mongo Atlas用户密码

const uri = "mongodb+srv://duke:[email protected]/test?retryWrites=true&w=majority";
© www.soinside.com 2019 - 2024. All rights reserved.