MongoClient和我们在MongoClient.connect()方法的回调中获得的客户端对象之间有什么区别

时间:2018-08-17 06:05:15

标签: node.js mongodb node-mongodb-native

const { MongoClient, ObjectID } = require('mongodb');
const debug = require('debug')('mongodb-connect');

MongoClient.connect('mongodb://localhost:27017/TodoApp', { useNewUrlParser: true }, (err, client) => {
  if (err) return debug(`Unable to connect to the server ${err}`);
  debug('Connected to the server');
  const db = client.db('TodoApp');
  db.collection('Todos').insertOne({
    text: 'Something to do',
    completed: false,
  }, (error, result) => {
    if (err) return debug(`There was a problem while inserting, ${error}`);
    debug(`Data inserted successfully ${JSON.stringify(result.ops, undefined, 2)}`);
  });
  client.close();
});

现在在上面的代码中,我有一个MongoClient对象,我调用了MongoClient.connect()方法将Node应用程序与本地数据库服务器连接。在回调中,我获得了另一个用于执行数据库操作的客户端对象。我对区分两个对象感到困惑:MongoClient和client(来自回调)

2 个答案:

答案 0 :(得分:0)

MongoClient是您从mongodb包中导入的类的名称。

MongoClient.connect()是该类的静态方法。它会创建MongoClient(您的client对象)的实际实例,并将其传递给您的回调。

您不能真正完成MongoClient,因为它只是实际客户的表示形式/类。这不是您可以调用任何方法的实例。

仅通过调用MongoClient.connect,您将获得该类的实例,您可以将该实例实际用于与MongoDB一起使用。

答案 1 :(得分:0)

除了List<Person> sortedListOfPeopleByPredicateMatchCOunt = listPersArrays .asList(listPersons) .stream() .sorted( Comparator.comparingLong(p -> predicates.stream().filter(predicate -> predicate.test(p)).count())) // Reverse because we want higher numbers to come first. .reversed()) .collect(Collectors.toList()); 之外什么都没有。

您应该查看this。 Mongo团队提供了详细记录的解释。

  1. MongoClient:用于通过URL连接。
  2. mongoClient(client)作为参数:如果连接成功,将返回数据库对象。