четверг, 13 апреля 2017 г.

MongoDB - введение

1) Скачать и инсталлировать базу данных MongoDB.
2) Создать папку с проектом под именем "myproject".
3) Установить в папку "myproject" Node.js, NPM и выполнить команду в командной строке:

npm install mongodb

4) Создать в папке "myproject" папку с именем "data".
5) Создать в папке "myproject" файл с именем "app.js" со следующим кодом в нём:

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  db.close();
});

6) Запустить сервер MongoDB из командной строки командой:

"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe" --dbpath=D:\myproject\data

Обращаю внимание, что для правильного выполнения данной команды папка "data" в папке "myproject" должна уже существовать.

7) Запустить на выполнение файл "app.js" из командной строки командой:

node.exe app.js

В результате успешного его выполнения в командной строке появится сообщение:

Connected successfully to server

8) Вставка данных в базу данных выполняется с помощью следующего кода в файле "app.js":

var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function (err, db) {
    assert.equal(null, err);
    console.log("Connected successfully to server");
    insertDocuments(db, function() {
        db.close();
    });
});

function insertDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

9) Запустить на выполнение файл "app.js" из командной строки командой:

node.exe app.js

В результате успешного его выполнения в командной строке появится сообщение:

Connected successfully to server
Inserted 3 documents into the collection

10) Выборка всех данных из базы данных выполняется с помощью следующего кода в файле "app.js":

var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function (err, db) {
    assert.equal(null, err);
    console.log("Connected successfully to server");
    // insertDocuments(db, function() {
        findDocuments(db, function() {
            db.close();
        });
    // });
});

function insertDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function findDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

11) Запустить на выполнение файл "app.js" из командной строки командой:

node.exe app.js

В результате успешного его выполнения в командной строке появится сообщение:

Connected successfully to server
Found the following records
и далее список найденных записей, которые мы добавили на шаге 9

12) Выборка конкретных данных из базы данных выполняется с помощью следующего кода в файле "app.js":

var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function (err, db) {
    assert.equal(null, err);
    console.log("Connected successfully to server");
    // insertDocuments(db, function() {
        findDocuments(db, function() {
            db.close();
        });
    // });
});

function insertDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function findDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

13) Запустить на выполнение файл "app.js" из командной строки командой:

node.exe app.js

В результате успешного его выполнения в командной строке появится сообщение:

Connected successfully to server
Found the following records
и далее список найденных записей

14) Обновление данных в базе данных выполняется с помощью следующего кода в файле "app.js":

var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function (err, db) {
    assert.equal(null, err);
    console.log("Connected successfully to server");
    // insertDocuments(db, function() {
        // findDocuments(db, function() {
            updateDocument(db, function() {
                db.close();
            });
        // });
    // });
});

function insertDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function findDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function updateDocument (db, callback) {
    // Get the documents collection
    var 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);
    });
}

14) Запустить на выполнение файл "app.js" из командной строки командой:

node.exe app.js

В результате успешного его выполнения в командной строке появится сообщение:

Connected successfully to server
Updated the document with the field a equal to 2

15) Удаление данных из базы данных выполняется с помощью следующего кода в файле "app.js":

var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function (err, db) {
    assert.equal(null, err);
    console.log("Connected successfully to server");
    // insertDocuments(db, function() {
        // findDocuments(db, function() {
             // updateDocument(db, function() {
                    removeDocument(db, function() {
                        db.close();
                    });
             // });
        // });
    // });
});

function insertDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function findDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function updateDocument (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function removeDocument (db, callback) {
    // Get the documents collection
    var 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);
    });
}

16) Запустить на выполнение файл "app.js" из командной строки командой:

node.exe app.js

В результате успешного его выполнения в командной строке появится сообщение:

Connected successfully to server
Removed the document with the field a equal to 3

17) Проведение индексирование данных для увеличения производительности выполняется с помощью следующего кода в файле "app.js":

var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function (err, db) {
    assert.equal(null, err);
    console.log("Connected successfully to server");
    // insertDocuments(db, function() {
        // findDocuments(db, function() {
             // updateDocument(db, function() {
                  // removeDocument(db, function() {
                        indexCollection(db, function() {
                            db.close();
                        });
                  // });
             // });
        // });
    // });
});

function insertDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function findDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function updateDocument (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function removeDocument (db, callback) {
    // Get the documents collection
    var 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);
    });
}

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

18) Запустить на выполнение файл "app.js" из командной строки командой:

node.exe app.js

В результате успешного его выполнения в командной строке появится сообщение:

Connected successfully to server
a_1

19) Поиск и обноввление данных в базе данных выполняется с помощью следующего кода в файле "app.js":

var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function (err, db) {
    assert.equal(null, err);
    console.log("Connected successfully to server");
    // insertDocuments(db, function() {
        // findDocuments(db, function() {
             // updateDocument(db, function() {
                  // removeDocument(db, function() {
                        // indexCollection(db, function() {
                                findAndUpdate(db, function() {
                                    db.close();
                                });
                        // });
                  // });
             // });
        // });
    // });
});

function insertDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function findDocuments (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function updateDocument (db, callback) {
    // Get the documents collection
    var 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);
    });
}

function findAndUpdate (db, callback) {
    var collection = db.collection('documents');
    collection.findOneAndUpdate({b : 2},  {$set: {b : 3}}, function (err, result) {
        assert.equal(err, null);
        console.log("Updated the document with the field a equal to 2");
        callback(result);
    });
}

function removeDocument (db, callback) {
    // Get the documents collection
    var 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);
    });
}

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

20) Запустить на выполнение файл "app.js" из командной строки командой:

node.exe app.js

В результате успешного его выполнения в командной строке появится сообщение:

Connected successfully to server
Updated the document with the field a equal to 2

воскресенье, 9 апреля 2017 г.

11 примеров вызовов функций в JavaScript

console.log(1);
(_ => console.log(2))();
eval('console.log(3);');
console.log.call(null, 4);
console.log.apply(null, [5]);
new Function('console.log(6)')();
Reflect.apply(console.log, null, [7])
Reflect.construct(function(){console.log(8)}, []);
Function.prototype.apply.call(console.log, null, [9]);
Function.prototype.call.call(console.log, null, 10);
new (require('vm').Script)('console.log(11)').runInThisContext();