简体   繁体   English

MongoDB node.js驱动程序和和尚

[英]MongoDB node.js driver and monk

I am using the mongodb driver and monk on nodejs. 我在nodejs上使用mongodb驱动程序和monk。 Examples such as this that I see on the Web have the following pattern: 举例如这个 ,我在网络上看到有以下模式:

var mongo = require('mongodb');
var monk = require('monk');

var db = monk('localhost:27017/userdb');
var collection = db.get('users');
collection.find({}, function(err, docs) {
    // do something with docs
});

Two questions: 两个问题:

  1. Why is the first line needed: var mongo = require('mongodb')? 为什么需要第一行:var mongo = require('mongodb')? The variable mongo is never used. 永远不会使用变量mongo。 Wouldn't monk automatically require mongodb? 僧人不会自动要求mongodb吗?
  2. I see at the driver level, the db has to be opened and closed. 我在驱动程序级别看到db必须打开和关闭。 These methods don't seem to exist at the monk level. 这些方法似乎并不存在于和尚级别。 Does monk automatically open and close connections? 和尚自动打开和关闭连接吗? How does this work? 这是如何运作的?

As a matter of fact, I am wondering what advantage does monk provide over using the driver directly. 事实上,我想知道和尚提供了直接使用驱动程序的优势。 I read the list of features in the monk docs , but don't really understand the benefits. 我阅读了僧侣文档中的功能列表,但并不真正理解其中的好处。

Thanks in advance for your help. 在此先感谢您的帮助。

To answer some of the specifics, based on my own experience: 根据我自己的经验回答一些具体细节:

1) You are correct that the mongodb variable is not required. 1)你是正确的,不需要mongodb变量。 I don't know why it appears in all the tutorials. 我不知道为什么它出现在所有教程中。 However, mongodb IS required as a dependency, additional to monk. 但是,除了和尚之外,mongodb IS还需要作为依赖。

2) As you suspected, you do need to call db.close(), otherwise the connection stays open. 2)如您所料,您需要调用db.close(),否则连接保持打开状态。 This doesn't seem to be documented anywhere. 这似乎没有在任何地方记录。 When you follow that tutorial you can see the number of open connections to your local mongodb growing. 按照该教程,您可以看到本地mongodb增长的打开连接数。

As you've probably read already, the goal of monk is to provide a friendlier API than mongodb's own driver. 正如您可能已经读过的那样,和尚的目标是提供比mongodb自己的驱动程序更友好的API。 I don't have enough experience with it to say whether or not it achieves that. 我没有足够的经验来说明它是否实现了这一点。

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

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