nodejsを使用してmongodbデータベースに接続する
6512 ワード
単純なnodejs接続mongodbの例ですmongodbの公式例から
1.packageを作成する.json
まず、プロジェクトディレクトリ
npm initコマンドを入力してpackageを作成します.json
その後、mongodbのnodejsバージョンdriver
2.MongoDBサーバの起動
MongoDBをインストールしてMongoDBデータベースサービスを開始するには、以前の記事やMongoDB公式ドキュメントを参照してください.
3.MongoDB接続
コマンドラインに次のコマンドを入力して
4.ドキュメントの挿入
コマンドラインで
5.すべての文書を問い合わせる
6.フィルタ条件を使用してドキュメントをクエリーする
クエリー'a':3のドキュメント
7.文書の更新
8.文書の削除
9.索引の作成
インデックスは、アプリケーションのパフォーマンスを改善します.次は「a」プロパティにインデックスを追加します.
更新
コードはすでにコードクラウドに管理されています
1.packageを作成する.json
まず、プロジェクトディレクトリ
connect-mongodb
を作成し、現在のディレクトリとして使用します.mkdir connect-mongodb
cd connect-mongodb
npm initコマンドを入力してpackageを作成します.json
npm init
その後、mongodbのnodejsバージョンdriver
npm install mongodb --save
mongodb
ドライバパッケージが現在のディレクトリのnode_にインストールされます.modulesで2.MongoDBサーバの起動
MongoDBをインストールしてMongoDBデータベースサービスを開始するには、以前の記事やMongoDB公式ドキュメントを参照してください.
3.MongoDB接続
app.js
ファイルを作成し、サーバアドレス192.168.0.243
、mongodbポート27017
のmyNewDatabase
という名前のデータベースに接続するコードを追加します.var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
// Connection URL
var url = 'mongodb://192.168.0.243:27017/myNewDatabase';
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connection successfully to server");
db.close();
});
コマンドラインに次のコマンドを入力して
app.js
node app.js
を実行します.4.ドキュメントの挿入
app.js
に次のコードを追加し、insertMany
メソッドを使用してdocuments
のセットに3つのドキュメントを追加します.var insertDocuments = function(db, callback){
// get ths 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);
});
};
insert
コマンドは、次の属性を含むオブジェクトを返します.result
MongoDBが返す文書結果ops
が追加されました_idフィールドのドキュメントconnection
挿入操作に用いるconnection app.js
で次のコード呼び出しinsertDocuments
メソッドを更新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();
});
});
コマンドラインで
node app.js
を使用して実行5.すべての文書を問い合わせる
findDocuments
関数の追加var findDocuments = function(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);
});
};
findDocuments
関数は、すべての「documents」セット内のすべてのドキュメントをクエリーし、この関数をMongoClientに追加します.connectのコールバック関数で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 correctly to server");
insertDocuments(db, function() {
findDocuments(db, function() {
db.close();
});
});
});
6.フィルタ条件を使用してドキュメントをクエリーする
クエリー'a':3のドキュメント
var findDocuments = function(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);
});
}
7.文書の更新
var updateDocument = function(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);
});
};
updateDocument
メソッドは、条件aが2である最初のドキュメントを更新し、b属性を追加し、1に設定する.updateDocument
メソッドをMongoClient.connect
メソッドのコールバックに追加MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connection successfully to server");
insertDocuments(db,function(){
updateDocument(db,function(){
db.close();
});
});
});
8.文書の削除
var removeDocument = function(db,callback){
// get the documents collection
var collection = db.collection('documents');
// remove some 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);
});
};
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() {
updateDocument(db, function() {
removeDocument(db, function() {
db.close();
});
});
});
});
9.索引の作成
インデックスは、アプリケーションのパフォーマンスを改善します.次は「a」プロパティにインデックスを追加します.
var indexCollection = function(db,callback){
db.collection('documents').createIndex({
a:1
},null,function(err,results){
console.log(results);
callback();
});
};
更新
app.js
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connection successfully to server");
insertDocuments(db,function(){
indexCollection(db,function(){
db.close();
});
});
});
コードはすでにコードクラウドに管理されています