nodejs use for data persistence mongodb

Some time ago, wrote a blog, explained the use of brew mongodb installation under Mac , this article can be seen as a sequel, using nodejs operation mongodb, and package some useful methods.

nodejs mongodb operation, the first to use a package npm install the operating mongodb database, there are two options mongoose and mongodb , due to the use of mongodb closer mongodb native syntax, so here we use mongodb module, database operation.

In use under Mac brew install mongodb this article, has explained the nature of the installation and mongodb database also introduced a connected mongodb client tools Robomongo, so here is not in the repeat.

However, a brief grammar at mongodb database is still necessary, if you already know, you can skip this, then we use the syntax to do a native CURD operations.

1, start the service mongodb

mongo

Mongo execute commands in a terminal can start mongodb service, we will enter the interactive mode mongo, as:

Start mongodb Service

We can see that after mongo start, the default connection is the test database, attention, mongodb non-relational databases, and MySQL is different in mongodb in:

nodql           <=====>        sql
数据库(database) <=====> 数据库(database)
集合(collection) <=====> 表(table)
文档(docs)         <=====> 行(rows)
字段(field)         <=====> 列(field)

We execute the following command to view the database of our current operations:

db

Below, our current database operation is test library:

We currently display database operated by

You can also execute the following command to view the database so:

show dbs

As shown below, demonstrate all of our databases, but please note that if you do not have any data inside the database, will not be showing up:

Displays all the database, the database is not empty display

We can use the following command to switch the database:

use hcy

In this way, we will switch to a database named hcy database, we can execute db command to see if the handover success:

Switching Database

Note that using use db_name to switch the database, if the database does not exist, it will create the database, so if you want to create a database, but also with the use Jiuhaola command.

If you want to delete a database, we first need to switch to the current database, and then execute the following command you can delete the database:

use hcy

db.dropDatabase()

This will delete hcy this database, we come to see all the database, find hcy libraries have gone, we have been deleted:

Delete Database

Here, we describe the simplest curd operations:

1, a collection of documents to insert a hcy database users

If the words of the title translated into the language sql database is: "insert a row into hcy database users table," then we look at how to mongodb collection database into a document:

use hcy

db.users.insert({
    name : 'hcy',
    age : 21
})

First, we switched to hcy database, if the database does not automatically create the database, and then perform operations insert data, we can use the following command to query a data set:

db.users.find()

This will check out all the data hcy database users a collection of the following, if the conditions required to find, like the following command, only need to pass the find () method in a json object as a filter criteria can be:

db.users.find({name:'hcy'})

delete data:

db.users.remove()

The above data will be deleted at the set of users get all documents (data), can also pass the first argument, as the filter criteria:

db.users.remove({
    name : 'hcy'
})

The above command will delete users in the collection, all documents of all name hcy value, can also pass the second parameter is a boolean value, true to delete only one:

db.users.remove({
    name : 'hcy'
}, true)

There are two ways to modify the data, use the update () method may be used save () method, first look update () method:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

query: query update, similar to the back where within sql update query.
update: update objects and some of the newer operators (e.g., $, $ inc is ...) and the like, may be understood as a set behind the SQL update query
upsert: Alternatively, this parameter means that, if the update record does not exist, whether to insert objNew, true inserted, the default is false, not inserted.
multi: Optional, mongodb default is false, only updating the first record found, if this parameter is true, according to the conditions put many records to check out all the updates.
writeConcern: Optional, throw-level exception.

Here I only describes the syntax, you can also use the save () method:

db.collection.save(
   <document>,
   {
     writeConcern: <document>
   }
)

document: the document data.
writeConcern: Optional, throw-level exception.

Examples are as follows:

db.users.save({
    "_id" : ObjectId("56064f89ade2f21f36b03136"),
    "name" : "aaaa",
    "age" : "100"
})

In the above example, we replaced the _id of the document data 56064f89ade2f21f36b03136.

If you want to know more mongodb native grammar, here it is a good place

Now, you should have some understanding of mongodb, then how do we operate in nodejs mongodb in it?

The first to use npm install the module in the project mongodb

npm install --save mongodb

When we want to use this module to operate the database in the project, we can introduce the module

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

The above code returns a client mongodb instance, connection database:

var mongoConnectUrl = 'mongodb://localhost:27017/hcy';
MongoClient.connect(mongoConnectUrl, function(err, db){
    if(err) return console.log(err);
    console.log('连接成功');
});

The above mongoConnectUrl is connected to a url mongodb our database, attention, mongodb default listening port is 27017, in addition, if the connection is always unsuccessful, you can replace localhost ip address of your computer to try, in the time I tested use only ip address, the connection fails always use localhost, the last url that you want to connect to the database, here we hcy connect to the database.

After a successful connection to the database, we can create a set, and operation of the data inside a package we Method:

Insert data

/**
 * 插入数据
 * @method insertData
 * @param {String} mongoConnectUrl 数据库连接
 * @param {String} coll 集合名称
 * @param {Array} data 插入的数据
 * @param {Function} callback 回调函数
 * @return {Null}
 *
 */
function insertData(mongoConnectUrl, coll, data, callback){
    MongoClient.connect(mongoConnectUrl, function(err, db){
        if(err) return console.log(err);
        // 打开集合
        var collection = db.collection(coll);
        // 插入数据
        collection.insertMany(data, function(err, result){
            //console.log(result)
            // 记得要关闭数据库
            db.close();
            callback(result);
        });

    });
}

Query data

/**
 * 查询数据
 * @method findData
 * @param {String} mongoConnectUrl 数据库连接
 * @param {String} coll 集合名称
 * @param {Object} opation 条件
 * @param {Function} callback 回调函数
 * @return {Null}
 *
 */
function findData(mongoConnectUrl, coll, opation, callback){
    MongoClient.connect(mongoConnectUrl, function(err, db){
        if(err) return console.log(err);
        // 打开集合
        var collection = db.collection(coll);
        // 根据条件查询数据
        var userData = collection.find(opation);
        // 遍历数据
        userData.toArray(function(err2, docs) {
            // docs是查询出来的文档,json对象,可以打印出来看看
            db.close();
            callback(docs);
        });

    });
}

delete data

/**
 * @method deleteData
 * @param {String} mongoConnectUrl 数据库连接
 * @param {String} coll 集合名称
 * @param {Object} opation 条件
 * @param {Number} num 删除数据的数量,即删除几条
 * @return {Null}
 *
 */
function deleteData(mongoConnectUrl, coll, opation, num, callback){
    var i = num;
    var res = [];
    var tempRes = [];
    var thisFn = arguments.callee;
    MongoClient.connect(mongoConnectUrl, function(err, db){
        if(err) return console.log(err);

        var collection = db.collection(coll);
        if(i > 0){
            i--;
            collection.deleteOne(opation, function(err, result){
                // console.log(result)
                res.push(result);
                thisFn(mongoConnectUrl, coll, opation, i, callback);
                if(i == 0){
                    db.close();
                    tempRes = res;
                    res = []
                    i = 0;
                    callback(tempRes);
                }

            });
        }

    });
},

Modify a data

/**
 * @method deleteData
 * @param {String} mongoConnectUrl 数据库连接
 * @param {String} coll 集合名称
 * @param {Object} opation 条件
 * @param {Object} data 更新的数据
 * @return {Null}
 *
 */
function deleteData(mongoConnectUrl, coll, opation, data, callback){
    MongoClient.connect(mongoConnectUrl, function(err, db){
        if(err) return console.log(err);

        var collection = db.collection(coll);

        collection.updateOne(opation, { $set: data }, function(err, result) {
            db.close();
            callback(result);
        });

    });
},

Original: Big Box  nodejs use for data persistence mongodb


Guess you like

Origin www.cnblogs.com/petewell/p/11611876.html