我是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完整堆栈,而我在连接中花费了太多时间。
这是我得到的错误:
(节点:5284)DeprecationWarning:不建议使用当前的“服务器发现和监视”引擎,并将在以后的版本中将其删除。要使用新的“服务器发现和监视”引擎,请将选项{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;
,错误是: 服务器选择在30000毫秒后超时没有问题 [nodemon]应用程序崩溃-等待文件更改,然后再开始...
亲切的问候,