const node_modules_path = '../node_modules/'

// crypto-js - npm https://www.npmjs.com/package/crypto-js
const CryptoJS = require(node_modules_path + 'crypto-js')
// Encrypt
const ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123')
// Decrypt
const bytes = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123')
const plaintext = bytes.toString(CryptoJS.enc.Utf8)
console.log(plaintext) const mongoCfg = {
uri: 'mongodb://hbaseU:123@192.168.3.103:27017/hbase',
dbName: 'hbase'
}
const MongoClient = require(node_modules_path + 'mongodb').MongoClient
const assert = require(node_modules_path + 'assert') // Use connect method to connect to the server
MongoClient.connect(mongoCfg.uri, function (err, client) {
assert.equal(null, err)
console.log('Connected successfully to server')
const db = client.db(mongoCfg.dbName)
insertDocuments(db, function () {
console.log('cb..')
})
client.close()
}) const insertDocuments = function (db, callback) {
// Get the documents collection
const collection = db.collection('documents')
// Insert some documents
collection.insertMany([
{a: 1}, {a: 2}, {a: 3}
], function (err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
})
}

Description

The official MongoDB driver for Node.js. Provides a high-level API on top of mongodb-corethat is meant for end users.

NOTE: v3.x was recently released with breaking API changes. You can find a list of changeshere.

MongoDB Node.JS Driver

what where
documentation http://mongodb.github.io/node-mongodb-native
api-doc http://mongodb.github.io/node-mongodb-native/3.1/api
source https://github.com/mongodb/node-mongodb-native
mongodb http://www.mongodb.org

Bugs / Feature Requests

Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a case in our issue management tool, JIRA:

  • Create an account and login jira.mongodb.org.
  • Navigate to the NODE project jira.mongodb.org/browse/NODE.
  • Click Create Issue - Please provide as much information as possible about the issue type and how to reproduce it.

Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are public.

Questions and Bug Reports

Change Log

Change history can be found in HISTORY.md.

Installation

The recommended way to get started using the Node.js 3.0 driver is by using the npm (Node Package Manager) to install the dependency in your project.

MongoDB Driver

Given that you have created your own project using npm init we install the MongoDB driver and its dependencies by executing the following npm command.

npm install mongodb --save

This will download the MongoDB driver and add a dependency entry in yourpackage.json file.

You can also use the Yarn package manager.

Troubleshooting

The MongoDB driver depends on several other packages. These are:

The kerberos package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install thekerberos module. Furthermore, the kerberos module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install.

Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.

Diagnosing on UNIX

If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps.

git clone https://github.com/mongodb-js/kerberos
cd kerberos
npm install

If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install node-gyp globally:

npm install -g node-gyp

If it correctly compiles and runs the tests you are golden. We can now try to install themongod driver by performing the following command.

cd yourproject
npm install mongodb --save

If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.

npm --loglevel verbose install mongodb

This will print out all the steps npm is performing while trying to install the module.

Diagnosing on Windows

A compiler tool chain known to work for compiling kerberos on Windows is the following.

  • Visual Studio C++ 2010 (do not use higher versions)
  • Windows 7 64bit SDK
  • Python 2.7 or higher

Open the Visual Studio command prompt. Ensure node.exe is in your path and installnode-gyp.

npm install -g node-gyp

Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild:

git clone https://github.com/christkv/kerberos.git
cd kerberos
npm install
node-gyp rebuild

This should rebuild the driver successfully if you have everything set up correctly.

Other possible issues

Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there).

Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed.

Quick Start

This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the tutorials.

Create the package.json file

First, create a directory where your application will live.

mkdir myproject
cd myproject

Enter the following command and answer the questions to create the initial structure for your new project:

npm init

Next, install the driver dependency.

npm install mongodb --save

You should see NPM download a lot of files. Once it's done you'll find all the downloaded packages under the node_modules directory.

Start a MongoDB Server

For complete MongoDB installation instructions, see the manual.

  1. Download the right MongoDB version from MongoDB
  2. Create a database directory (in this case under /data).
  3. Install and start a mongod process.
mongod --dbpath=/data

You should see the mongod process start up and print some status information.

Connect to MongoDB

Create a new app.js file and add the following code to try out some basic CRUD operations using the MongoDB driver.

Add code to connect to the server and the database myproject:

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();
});

Run your app from the command line with:

node app.js

The application should print Connected successfully to server to the console.

Insert a Document

Add to app.js the following function which uses the insertMany method to add three documents to the documents collection.

const insertDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Insert some documents
  collection.insertMany([
    {a : 1}, {a : 2}, {a : 3}
  ], function(err, result) {
    assert.equal(err, null);
    assert.equal(3, result.result.n);
    assert.equal(3, result.ops.length);
    console.log("Inserted 3 documents into the collection");
    callback(result);
  });
}

The insert command returns an object with the following fields:

  • result Contains the result document from MongoDB
  • ops Contains the documents inserted with added _id fields
  • connection Contains the connection used to perform the insert

Add the following code to call the insertDocuments function:

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);
 
  insertDocuments(db, function() {
    client.close();
  });
});

Run the updated app.js file:

node app.js

The operation returns the following output:

Connected successfully to server
Inserted 3 documents into the collection

Find All Documents

Add a query that returns all the documents.

const findDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Find some documents
  collection.find({}).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs)
    callback(docs);
  });
}

This query returns all the documents in the documents collection. Add the findDocumentmethod to the MongoClient.connect callback:

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 correctly to server");
 
  const db = client.db(dbName);
 
  insertDocuments(db, function() {
    findDocuments(db, function() {
      client.close();
    });
  });
});

Find Documents with a Query Filter

Add a query filter to find only documents which meet the query criteria.

const findDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Find some documents
  collection.find({'a': 3}).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs);
    callback(docs);
  });
}

Only the documents which match 'a' : 3 should be returned.

Update a document

The following operation updates a document in the documents collection.

const updateDocument = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Update document where a is 2, set b equal to 1
  collection.updateOne({ a : 2 }
    , { $set: { b : 1 } }, function(err, result) {
    assert.equal(err, null);
    assert.equal(1, result.result.n);
    console.log("Updated the document with the field a equal to 2");
    callback(result);
  });  
}

The method updates the first document where the field a is equal to 2 by adding a new fieldb to the document set to 1. Next, update the callback function from MongoClient.connect to include the update method.

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);
 
  insertDocuments(db, function() {
    updateDocument(db, function() {
      client.close();
    });
  });
});

Remove a document

Remove the document where the field a is equal to 3.

const removeDocument = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Delete document where a is 3
  collection.deleteOne({ a : 3 }, function(err, result) {
    assert.equal(err, null);
    assert.equal(1, result.result.n);
    console.log("Removed the document with the field a equal to 3");
    callback(result);
  });    
}

Add the new method to the MongoClient.connect callback function.

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);
 
  insertDocuments(db, function() {
    updateDocument(db, function() {
      removeDocument(db, function() {
        client.close();
      });
    });
  });
});

Index a Collection

Indexes can improve your application's performance. The following function creates an index on the a field in the documents collection.

const indexCollection = function(db, callback) {
  db.collection('documents').createIndex(
    { "a": 1 },
      null,
      function(err, results) {
        console.log(results);
        callback();
    }
  );
};

Add the indexCollection method to your app:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
 
// Connection URL
const url = 'mongodb://localhost:27017';
 
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);
 
  insertDocuments(db, function() {
    indexCollection(db, function() {
      client.close();
    });
  });
});

For more detailed information, see the tutorials.

Next Steps

install

npm i mongodb

weekly downloads

710,340.000

version

3.1.4

license

Apache-2.0

open issues

0

pull requests

13

homepage

github.com

repository

github

last publish

9 days ago

												

借助nodejs解析加密字符串 node安装库较python方便的更多相关文章

  1. C++解析(18):C++标准库与字符串类

    0.目录 1.C++标准库 2.字符串类 3.数组操作符的重载 4.小结 1.C++标准库 有趣的重载--操作符 << 的原生意义是按位左移,例:1 << 2;,其意义是将整数 ...

  2. 《Nodejs开发加密货币》之二十七:开发通用的HTML组件

    人的懒惰常常是麻烦的开始.多数程序员都希望自己的工作一劳永逸,一次开发,到处使用,成了人人追逐的目标,我也不例外.最初写<Nodejs开发加密货币>系列文章,因为不喜欢设定好了去写,所以目 ...

  3. Ubuntu 16.04 LTS nodejs+pm2+nginx+git 基础安装及配置环境(未完,未整理)

    -.Ubuntu 安装nodejs 以下内容均在命令行,完成,首先你要去你电脑的home目录:cd ~. [sudo] apt-get update [sudo] apt-get upgrade ap ...

  4. Java和NodeJS解析XML对比

    Java解析XML 1.接收xml文件或者字符串,转为InputStream 2.使用DocumentBuilderFactory对象将InputStream转为document对象 Document ...

  5. linux md5 加密字符串和文件方法

    linux md5 加密字符串和文件方法 MD5算法常常被用来验证网络文件传输的完整性,防止文件被人篡改.MD5全称是报文摘要算法(Message-Digest Algorithm 5),此算法对任意 ...

  6. 利用 nodejs 解析 m3u8 格式文件,并下 ts 合并为 mp4

    利用 nodejs 解析 m3u8 格式文件,并下 ts 合并为 mp4 以前看视频的时候,直接找到 video标签,查看视频地址,然后下载下来.. 后来发现,好多 video 标签打开元素审查,如下 ...

  7. Cannot install NodeJs: /usr/bin/env: node: No such file or directory

    安装doxmate时,doxmate地址是:https://github.com/JacksonTian/doxmatenpm install doxmate -g 安装完后把错误:Cannot in ...

  8. nodejs系列(一)安装和介绍

    一.安装nodejs http://www.nodejs.org/download/.进入release/选择想要安装的文件,win下安装选择mis和exe的比较方便,安装完毕重新打开cmd命令行,p ...

  9. GitBook是一个命令行工具(Node.js库),我们可以借用该工具使用Github/Git和Markdown来制作精美的图书,但它并不是一本关于Git的教程哟。

    GitBook是一个命令行工具(Node.js库),我们可以借用该工具使用Github/Git和Markdown来制作精美的图书,但它并不是一本关于Git的教程哟. 支持输出多种格式 GitBook支 ...

随机推荐

  1. 用python登录WeChat(微信) 实现自动回复(非常详细)

    如要转载 麻烦备注好原文出处!!! 最近实现了一些微信的简单玩法 我们可以通过网页版的微信微信网页版,扫码登录后去抓包爬取信息,还可以post去发送信息. >>安装itchat这个库    ...

  2. Mac环境下svn命令行的使用

    在Windows环境中,我们一般使用TortoiseSVN来搭建svn环境.在Mac环境下,由于Mac自带了svn的服务器端和客户端功能,所以我们可以在不装任何第三方软件的前提下使用svn功能,不过还 ...

  3. Fatal error: Call to a member function read() on a non-object in

    是你的路径出问题了系统 > 系统基本参数 > 站点设置 里面的<站点根网址:和 网页主页链接:>系统 > 系统基本参数 > 核心设置 <DedeCMS安装目录 ...

  4. 15.【nuxt起步】-Nuxt使用jsweixin sdk

    npm install weixin-js-sdk --save 这个不行,这个是vue前端用的 网上找了一些vue jsweixin的案例 不能直接用 因为nuxt是后端运行,windows对象取不 ...

  5. 2017.2.16 开涛shiro教程-第十七章-OAuth2集成(二)客户端

    原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. 开涛shiro教程-第十七章-OAuth2集成 3.客户端 客户端 ...

  6. MongoDB基本文件操作

    MongoDB中主要的文件操作有put.get.list.search几种.能够非常方便地进行文件存储于查找,下面是一个简单的演示样例. 1.利用dd命令生成要求大小随机文件  2.使用put命令将生 ...

  7. props default 数组(Array)/对象(Object)的默认值应当由一个工厂函数返回

    1.场景: Object: <!-- 步骤 --> <template> <div> <div class="m-cell"> &l ...

  8. 翻翻git之---一个丰富的通知工具类 NotifyUtil

    转载请注明出处王亟亟的大牛之路 P1(废话板块.今天还加了个小广告) 昨天出去浪,到家把麦麦当当放出来玩一会就整到了12点多..早上睡过头了. .简直心酸. ... 近期手头上有一些职位能够操作,然后 ...

  9. UDP最大传输字节

    每个包最大可携带字节长度:65507个byte. 封装成 IP 后,大小超出 PMTU 的分组将可能被 fragmented. 如果设置了 Don't Frag,超出 PMTU 的分组将不能被发送. ...

  10. 在VS2010中如何添加MSCOMM控件,实现串口通讯

      参考文章:http://wenku.baidu.com/link?url=MLGQojaxyHnEgngEAXG8oPnISuM9SVaDzNTvg0oTSrrJkMXIR_6MR3cO_Vnh- ...