First taste of mongodb+node.js

Foreword: Those of you who do not write well in the backend of the interface must force the frontend to dominate the world. It's just a joke. It was the first time I wrote something related to the backstage. When the mystery of the backstage was lifted, the surprise, happiness, and sense of accomplishment brought me back to when I wrote the first hello world.

Since I am using the win10 system, it is based on windows. Linux and mac os can solve it by themselves, but they should be similar.

1. Installation

The download and installation of mongodb will not be mentioned. If you have not downloaded and installed it, you can go to the official website of Mongodb to download and install it.

2. Create data 

This part of the content mainly refers to  the articles of NodeJS+Express+MongoDB  . I mainly talk about the pits stepped on and the error handling encountered.

After installation, create a data folder in the root directory, which I put in the e drive.

e:\data\db is used to store the data files of mongodb

e:\data\log is used to store the log file of mongodb

  error handling

    1. A system error occurred when the MongoDB service was started using the net start mongodb command, and the return value was 5

      Solution: Open cmd as an administrator, go to C:\ Windows \System32 to find cmd.exe and run it as an administrator. In order to avoid searching for the cmd file every time I start it, I put cmd in the start menu, and right-click it and fix it in the start menu.

    2. An error occurred when starting the mongodb system using the net start mongodb command. System error 1067 has occurred. The process terminated unexpectedly.

      Solution: MongoDB installation directory \data\ delete mongod.lock in this folder, I have not encountered this problem, and I don't know if it can be solved correctly. If you have stepped on the pit, you can talk about it.

    3. An error occurred when starting the mongodb system using the net stop mongodb command. System error 1067 has occurred. The process terminated unexpectedly.

      I started normally when I started, but reported an error when I stopped, but finally stopped normally. I don't have the mongod.lock or mongod.cfg mentioned above, and I don't know how to solve it. I know how to solve it. Big brother please enlighten me, thank you, bow and bow!

    Note: After solving the problem, you must restart the service to take effect.

3. Start 

Or continue to refer to the previous article
    1. Command line
    ## Start service
    net start mongodb

    ## Stopping the service nginxstop will not close the service, you need to use kill, it turns out that stop under win10 is a
    net stop mongodb that can stop the service normally

    2. In the installation directory of mongodb, the mongo.exe file under E:\Program Files\MongoDB\Server\3.4\bin can also be placed in the start, right click and fix it in the start menu.

    3. Visualization tool robomongo

        Download the portal     and select Robo 3T, select the second green version, download it and unzip it and run the .exe file directly. Of course, this can also be placed in the start, right click and fix it in the start menu.

Robo 3T download screenshot

4. Administrator  

Refer to  Getting Started with NodeJS - Preparation (2) - MongoDB Installation and Client Robomongo Installation and Use
    1. Re-open a command line window and switch to the bin folder under the Mongodb installation path
    2. Enter the command: mongo, enter the command use admin switch to admin database
    3. Enter the command db.addUser('admin','admin') to add an administrator account This is the previous version The
    new version should use ad.createUser({user:"admin",pwd:"admin" ,roles:[]})  

    New version of the command reference

5. Database operations

Use the robo3T robomongo tool
    1. To create and delete databases,
        you can use the graphical interface to right-click create database to create a database, and right-click Drop Database to delete a database.
        You can also use the command line to operate:
            1. Create a database gomall: use gomall    
                                  db
            2. Delete a database gomall: use gomall
                                db.dropDatabase() 2. Database operation command:         first open the shell scripting interface 1.insert:             command: db.table name.insert(data);              example: db.products.insert({name:"iphone",price: 1988});             Description: The insert operation will automatically create the products table, _id, which is generated by mongodb itself, and each row of data will exist. The default is ObjectId, and the value of this key can be inserted when inserting data (supports all data types supported by mongodb. )             to view the data: db.getCollection('products').find({});             After version 3.2, the following syntaxes can be used to insert documents:
    

        





            db.collection.insertOne(): Insert a document data into the specified collection
            db.collection.insertMany(): Insert multiple document data into the specified collection
        2.save
            command: db.table name.save.(data);
            example : db.proctus.save({_id:2,name:"HuaWei P10",price:2999});
            Note: _id can be inserted by itself, and a table does not have to have the same fields, although both insert and save methods can be inserted Data, when the default "_id" value already exists, calling the insert method will report an error; while the save method will not, it will update the information of the row data where the same _id is located.
        3. Batch add
            for(var i = 0; i < 5; i ++) db.users.save({'_id':i,'name':'zhangguo'+i,'age':i+8} );
            for(let i = 0; i < 5; i ++) db.users.save({'_id':i,'name':`zhangguo${i}`,'age':i+8} );
        4. Query data
            1. Query all data in the collection
                Command: db.collection.find();
                Example: db.users.find({name:'
                     db.getCollection('users').find({}); 
                     db.users.find({});
                     db.users.find();
                Among them, the last three ways of writing in the example are the same result
            2. Query by condition (Supports multiple conditions)
                Command: db.set.find(condition);
                Example: db.users.find({name:'zhangguo0',age:9})
                Description: The condition requirements in the object are established at the same time
            3. Query the first Article (support condition)
                command: db.collection.findOne(condition);
                example: db.users.findOne({name:'zhangguo0'});
            4. Limit quantity
                command: db.collection.find().limit(quantity );
                Example: db.users.find({}).limit(3); or db.users.find().limit(3); Same result
            5. Skip the specified number
                command: db.tablename.find( ).skip(quantity);
                Example: db.users.find({}).skip(3); 
                      db.users.find({}).skip(2).limit(2);
            6. Comparison query

                 Different types will not be compared, string and number will not be compared

                Syntax Reference for Compare Queries


                1. Equal to: $eq
                    Format: {<key>:<value>}
                          {<key>:{$eq:<value>}}
                    Example: db.users.find({age:10});
                          db.users. find({age:{$eq:10}});
                    Description: The results of these two formats are the same
                2. Greater than: $gt 
                    format: {<key>:{$gt:<value>}}
                    Example: db .users.find({age:{$gt:10}});
                3. Greater than or equal to: $gte
                    format: {<key>:{$gte:<value>}}
                    Example: db.users.find({age :{$gte:10}});
                4. Less than: $ ltFormat
                    : {<key>:{$lt:<value>}}
                    Example: db.users.find({age:{$lt:10}} );
                5. Less than or equal to: $lte
                    Format: {<key>:{$lte:<value>}}
                    Example: db.users.find({age:{$lte:10}});
                6. Not equal to: $ne
                    Format: {<key>:{$ne:<value>}}
                    Example: db.users.find({age:{$ne:10}});
            7. Query quantity
                syntax: db.tablename.find() .count();
                Example: db.users.find({}).count()
            8. Sort
                 syntax: db.table name.find().sort({"field name":1});
                 Example: db. users.find({}).sort({}) cannot be written as db.users.find({}).sort() will report "Failed to parse: sort: undefined. 'sort' field must be of BSON type object. "
                            db.users.find({}).sort({age:-1,name:1});
                Description: 1: Indicates ascending order; -1: Indicates descending order; db.users.find({}).sort({}) If nothing is passed, it is sorted by default, and the default is to sort in ascending order by _id.
           9. Return
                syntax of the specified field: db .table name.find({},{"field name":0});
                Example: db.users.find({age:{$gt:9}},{_id:0,age:1,name:1 });
                Description: Parameter 1: Return 0: No return
        5. Modify
            1. Modify the first item that meets the conditions: update
                syntax: db.set.update({"conditional field name":"field value"},{$ set:{"Field name to be modified":"Modified field value"}});
                Example: db.users.update({age:{$eq:9}},{$set:{age:100} });
                      db.users.update({age:9},{$set:{age:100}});
                Note: The results of these two formats are the same. The previous save in the _id field already exists is a modification operation.
            2. Modify multiple items: updateMany
                Example: db.users.updateMany({age:{$gt:10}},{$set:{age:20}});
        6.
            Syntax: db.set.remove(condition);
            Example: db.users.remove({age:{$gte:10}}); // delete data with age >=10

6.node.js access Mongodb

    Premise: first create a simple project with nodejs

    Introducing mongodb into the current project does not need to be installed globally.

       npm install mongodb --save

    Create a new db.js file in the root directory of the project and use Node.js to operate MongoDB. Just run node db.js after writing.

The complete code for Node.js to operate MongoDB is attached below. The main point is that the API interface of versions 2.x and 3.0 and above is slightly different

// 引入客户端mongodb模块,获得客户端对象
const MongoClient = require('mongodb').MongoClient;
// 连接字符串
const DB_CONN_STR = 'mongodb://localhost:27017/gomall';

// 添加数据
const insertData = function (db, callback) {
  // 获得指定的集合
  let collection = db.collection('users');
  // 插入数据
  let data = [{
    _id: 9,
    name: 'rose',
    age: 23
  }, {
    _id: 10,
    name: 'mark',
    age: 24
  }];

  // collection.insert(data, function (err, result) {  // mongodb 2.x的写法 
  collection.insertMany(data, function (err, result) {
    // 如果存在错误
    if (err) {
      console.error('Error:', err);
      return;
    }

    // 调用传入的回调方法,将操作结果返回
    callback(result);
  });
}

// 修改数据
const updateData = function (db, callback) {
  // 获得指定的集合
  let collection = db.collection('users');
  // 要修改数据的条件,>=10岁的用户
  let where = {
    age: {
      $gte: 10
    }
  };
  // 要修改的结果
  let set = {
    $set: {
      age: 95
    }
  };

  collection.updateMany(where, set, function (err, result) {
    // 如果存在错误
    if (err) {
      console.error('Error:', err);
      return;
    }
    // 调用传入的回调方法,将操作结果返回
    callback(result);
  })
}

// 查询数据
const findData = function (db, callback) {
  let collection = db.collection('users');
  let where = {
    age: {
      $eq: '22'
    }
  };
  let set = {
    name: 1,
    age: 1
  };

  collection.find(where, set).toArray(function (err, result) {
    if (err) {
      console.error('Error:', err);
      return;
    }
    callback(result);
  });

  // 删除数据
  const deleteData = function (db, callback) {
    let collection = db.collection('users');
    let where = {
      age: {
        $eq: '21'
      }
    };
    collection.remove(where, function (err, result) {
      if (err) {
        console.error('Error:', err);
        return;
      }
      console.log(result);
      callback(result);
    })
  }



}

//使用客户端连接数据,并指定完成时的回调方法
// MongoClient.connect(DB_CONN_STR, function (err, db) {  // 2.x的写法
MongoClient.connect(DB_CONN_STR, {
  useNewUrlParser: true
}, function (err, client) {  3.0的写法
  if (err) {
    console.error('数据库连接失败');
    return;
  }
  console.log('连接成功');
  // 执行插入数据操作,调用自定义方法
  let db = client.db('gomall'); // 3.0的写法
  insertData(db, function (result) {
    // 显示结果
    console.log(result);
    // 关闭数据库
    client.close();
  });

  updateData(db, function (result) {
    // 显示结果
    console.log(result);
    client.close();
  });

  findData(db, function (result) {
    console.log(result);
    client.close();
  });
  deleteData(db, function (result) {
    console.log(result);
    client.close();
  })
});

original address

grateful:

1. https://www.cnblogs.com/best/p/6212807.html

2. https://www.cnblogs.com/zhaord/p/4229001.html

3.https://blog.csdn.net/u010523770/article/details/54599548

4.http://www.runoob.com/mongodb/mongodb-query.html

It was you who turned on a street light on my dark road, thank you!

The above is my record of stepping on the pit, I hope it will help you too.

May the light be with you

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324349137&siteId=291194637