Connecting to MongoDB over SSL with Node.js

前端 未结 3 1831
一整个雨季
一整个雨季 2020-12-14 23:11

How do I connect to a MongoDB-server over SSL using Node.js?

I\'ve read the sources of a few drivers (mongojs, mongodb-native) and I\'ve been googling a while now, b

3条回答
  •  孤街浪徒
    2020-12-14 23:15

    As suggested in the comments, the node-mongodb-native has everything needed.

    I got it up and running using the following:

    var mongo = require('mongodb');
    
    var server = new mongo.Server('HOSTNAME', 27017, { ssl: true });
    var db = new mongo.Db('NAME_OF_MY_DB', server, { w: 1 });
    var auth = { user: 'USERNAME', pass: 'PASSWORD' };
    
    db.open(function(err, db) {
      if (err) return console.log("error opening", err);
    
      db.authenticate(auth.user, auth.pass, function(err, result) {
        if (err) return console.log("error authenticating", err);
    
        console.log("authed?", result);
    
        db.collection('whatever').count(function(err, count) {
          if (err) return console.log("error counting", err);
    
          console.log("count", count);
          db.close()
        });
      });
    });
    

    Edit

    You can also do ssl from mongoose:

    mongoose.createConnection(connString, { server: { ssl: true }})
    

提交回复
热议问题