使用Node.js(Express)+ MongoDB

版本
– node:v6.9.4
– npm:3.10.10
– express:4.14.0
– mongoDB:v3.4.3
– node-mongodb-native:v2.2

安装MongoDB

$ brew install mongodb
# 起動確認
$ brew services start mongodb
$ brew services stop mongodb

创建一个仓库,安装Node的MongoDB npm软件包。
mongodb/node-mongodb-native

$ express -e mongodb-prot
$ cd mongodb-prot
$ npm install mongodb --save

这与主题无关,但为了进行文件更改后重新启动服务器,我会安装nodemon。

$ npm install -g nodemon
  "scripts": {
    "prestart": "eslint .", // eslint使う場合
    "start": "node ./bin/www",
    "dev": "nodemon ./bin/www"
  },

以一种自然的方式写。

 $ npm run dev

运行。(如果是通过自定义名称安装的 dev,不能像 npm dev 一样运行,而是需要运行 npm run hoge 或 npm run-script hoge)

请将话题转回到MongoDB,然后在代码库中创建一个用于MongoDB的文件夹。

$ pwd /path/to/mongodb-prot
$ mkdir data
// mongodb起動
$ mongod --dbpath=data

我們從這裡開始進行簡單的CRUD操作,使用MongoDB。

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017/mongodb-prot';

// insert
function insertDocuments(db, callback) {
    let collection = db.collection('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);
        });
}

// findAll
function findAllDocuments(db, callback) {
    let collection = db.collection('documents');
    collection.find({}).toArray(function(err, docs) {
        assert.equal(err, null);
        console.log('Found the following records');
        console.log(docs);
        callback(docs);
    });
}

// find
function findDocument(db, callback) {
    let collection = db.collection('documents');
    collection.find({'a': 3}).toArray(function(err, docs) {
        assert.equal(err, null);
        console.log('Found record');
        console.log(docs);
        callback(docs);
    });
}

// update
function updateDocment(db, callback) {
    const collection = db.collection('documents');
    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);
        });
}

// remove
function removeDocument(db, callback) {
    const collection = db.collection('documents');
    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);
    });
}

// 接続して、上記のCRUDを試していく(適宜組み合わせて下さい)
// 下記はinsertしてfindAllしてる
MongoCient.connect(url, function(err, db) {
    assert.equal(null, err);
    console.log('connection successfully to server');

    insertDocuments(db, function() {
        findAllDocuments(db, function() {
            db.close();
        })
    });
});

文件在这里。
http://mongodb.github.io/node-mongodb-native/2.2/quick-start/quick-start/

另外,也稍微看看mongo的shell。

# 起動
$ mongo

$ show dbs
$ use mongodb-prot
$ show collections

# ドキュメント数を確認(今回は'documents'と名付けたのでそれをチェック)
$ db.documents.count()

# findAll
$ db.documents.find({})

文件在这里。
https://docs.mongodb.com/getting-started/shell/client/

我会把这次修改过的代码也放在这里。
https://github.com/mazeltov7/mongodb-prot

广告
将在 10 秒后关闭
bannerAds