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(来自回调)
MongoClient
是您导入的类的名称mongodb
包裹。
MongoClient.connect()
是该类的静态方法。它创建了一个实际实例 of MongoClient
(your client
对象)并将其传递给您的回调。
你真的不能做太多事情MongoClient
,因为它只是实际客户端的表示/一类。它不是一个可以调用任何方法的实例。
只需拨打电话即可MongoClient.connect
,您将获得该类的一个实例,您可以实际使用它来处理 MongoDB。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)