繁体   English   中英

Node.js中的MongoDB这两种连接方式有什么区别

[英]What is the difference between these two ways of connecting to MongoDB in Node.js

我遇到了通过 Node.js 连接到 MongoDB 的两种不同方式。 有什么区别? 优点和缺点?

  1. 使用.connect() 方法
let express = require('express')
let mongodb = require('mongodb')

let app = express()
let db
let connectionString = ''
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(port)
})
  1. 使用.MongoClient.connect()如MongoDB驱动官方快速入门文档所示
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
 
// Connection URL
const url = 'mongodb://localhost:27017';
 
// Database Name
const dbName = 'myproject';
 
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");
 
  const db = client.db(dbName);
 
  client.close();
});

引入 MongoClient class 是为了使所有平台的界面现代化和统一。

与“旧”方式相比,它并没有真正提供任何好处(除了它默认打开了写确认),但鼓励您将 MongoClient 用于新应用程序。 似乎将来可能会弃用旧方法。

https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM