尝试连接到MongoDB Atlas时如何解决密码错误?

时间:2019-07-31 10:23:43

标签: javascript node.js string mongodb

尝试从我的mongdb atlas应用程序连接到Node时,我总是收到错误消息

这是我的代码

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = `mongodb+srv://username:passwordwithspeciacharacters$$!!22@cluster0-xxxxx.mongodb.net/test?retryWrites=true&w=majority`;

module.exports = {
  signup: (name, email, password) => {
    MongoClient.connect(url, (err, db) => {
      if (err) {
        console.log(err);
      } else {
        db.collection('user').insertOne({
            name: name,
            email: email,
            password: password
          },
          function(err, result) {
            assert.equal(err, null);
            console.log('Saved the user sign up details.');
          }
        );
      }
    });
  }
};

这是我遇到的错误

(node:9626) DeprecationWarning: current URL string parser is 
deprecated, and will be removed in a future version. To use the new 
parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Error: Password contains an illegal unescaped character

我该如何清除传递的密码?

2 个答案:

答案 0 :(得分:1)

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const crypto = require('crypto');

const url = `mongodb+srv://username:passwordwithspeciacharacters$$!!22@cluster0-xxxxx.mongodb.net/test?retryWrites=true&w=majority`;

module.exports = {
    signup: (name, email, password) => {
        MongoClient.connect(url ,{useNewUrlParser:true}, (err, db) => {
            if (err) {
                console.log(err);
            } else {
                db.collection('user').insertOne({
                    name: name,
                    email: email,
                    password: crypto
                        .createHmac('sha256', 'secret')
                        .update(password)
                        .digest('hex')
                },
                    function (err, result) {
                        assert.equal(err, null);
                        console.log('Saved the user sign up details.');
                    }
                );
            }
        });
    }
};

//以相同的方式在登录时匹配密码

答案 1 :(得分:0)

MongoDB密码是URL编码的,因此您应该使用encodeURIComponent。添加useNewUrlParser选项对象也可以修复警告。

MongoClient.connect(encodeURIComponent(url), { useNewURLParser: true }, (err, db) => {...});