首页 > 解决方案 > 如何使用 URL 连接到 MongoDB 服务器?

问题描述

我不知道在这个脚本中将 MongoDB 中数据库的 URL 放在哪里,例如url : mongodb:localhost/mydb. 我在介绍和教程中找不到任何答案。

  var MongoClient = require('mongodb').MongoClient

  var state = {
    db: null,
  }

  exports.connect = function(url, db, done) {
    if (state.db) return done();

    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true  }, function(err, client) {
      if (err) return done(err)
      state.db = client.db(db);
      done();
    });
  }

  exports.get = function() {
    return state.db;
  }

  exports.close = function(done) {
    if (state.db) {
      state.db.close(function(err, result) {
        state.db = null;
        state.mode = null;
        done(err);
      })
    }
  }

标签: node.jsmongodb

解决方案


您可以在选项参数中设置 DB。

    MongoClient.connect(url, { db: '' }, function(err, client) {
      ...
    });

https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html#connect


推荐阅读