August is the prelude to Leo, that August’s tail w or virgo, today is the last day of August, decided in his own mind awake, seize the August tail, take the time to write a classic tinkering with useful blog, but it really is too busy recently, from our friends get married, to meet old mama to Beijing, to the tour of qinghai, and then to friends visiting over the weekend, It’s packed to the brim. But it’s really fulfilling. Some friends should ask, friends married what are you busy, ha ha ha ha ha ha don’t think blind ah, I but the best man group inside the appearance level bear yo. How can I be the best man?? I am also full of question marks! And go out to play although a cold, although the first day of the weather is not beautiful, although very cold, there is so although, but we are very happy, finally did not leave regret. At present hope time is slow a few slow a few slow…… Good nonsense did not say, recently steal kung fu hurriedly toss about it. SQL learning do not know how much cost, but still do not want to go the conventional way, I want to do mongodb, first a small test, planning to use mongodb+ node +vue to make a small demo landing. Come on, show!

  • Mongo installation

    1. Install mongodb on a manual MAC

      Manually install mongodb to search a large number of degrees, this I do not want to mention, according to the above written step by step on the line.

    2. The brew installation mongo

      Installing mongodb with BREW is a big hole

      • brew install mongodb
        Copy the code

        Mongodb is no longer open source and can not be installed directly with the command above, but can still be installed with BREW

      • Brew tap mongodb/brew brew install [email protected]Copy the code

        Installation is successful, start and stop the service

      • brew services start mongodb-community
        brew services stop mongodb-community
        Copy the code

        Configuration file path: / usr/local/etc/mongod. Conf log file path: / usr/local/var/log/mongo/mongo. Log data directory path: / data/db bin directory path: / usr/local/Cellar/mongo – community / 4.2.6 / bin

      • Brew MongoDB is installed in /usr/local/cellar/by default. Brew list can be used to check all the brew installed software:

    3. Set the account and password

      • Show DBS // Query all databasesCopy the code
      • Use admin // Enter the admin database. After installing mongodb, there is one System and one Congfig databaseCopy the code
      • db.createUser({ user: "admin", pwd: "password", roles: [{ role: "userAdminAnyDatabase", db: "Admin"}]}) // Create an administrator account. The role of the administrator account in mongodb is userAdminAnyDatabase. The admin user manages accounts and cannot perform operations such as shutting down the database.Copy the code
      • Db. CreateUser ({user: "root", PWD: "password", roles: [{role: "root", db: "admin"}]}) // Create a super administrator root. Role: root. The root role is used to shut down the database. db.shutdownServer()Copy the code
      • Use yourdatabase to access your own database db.createUser({user: "user", PWD: "password",roles: [{role: "dbOwner", db: "Yourdatabase"}]}) //role: "dbOwner" represents the database owner role with the highest permissions for the database. For example, create index and so on. As the account administrator and super administrator, you can create users for your own database. At this time, you must switch to the local database to create a user, otherwise the created user still belongs to admin.Copy the code
      • Use admin db.auth("admin","password") // Delete a single user db.system.users.remove({user:"XXXXXX"}) // Delete all users db.system.users.remove({})Copy the code
    4. Connecting to the mongodb Database

      • Mongo // pit pit pit pit pit for a long time to find online said command, the final or their own English documents, or English documents more reliableCopy the code
      • > Switch to db XXX > db XXX >Copy the code
      • Show DBS // You can see that there is no new database // The new database needs to insert data into the new database to displayCopy the code
      • db.xxx.insert({"name":"yuhior"})   // 
        Copy the code
    5. Robo T3 is a visualization tool similar to navact for mysql

  • The node connected mongo

    1. Install the Node scaffolding I used for KOA2

      npm install -g koa-generator
      Copy the code
    2. Create a project file directory

      Koa2 -- HBS KOA2-ZCLS // Handlebars templateCopy the code
    3. Install dependencies

      npm install 
      Copy the code
    4. The directory structure adds its own DB folder

      --bin
      	--www
      --db
      	--db.js
      	--index.js
      --node_modules
      --public
      	--images
      	--javascripts
      	--stylesheets
      --routes
      	--index.js
      	--users.js
      --views
      	--error.hbs
      	--index.hbs
      	--layout.hbs
      --app.js
      package.json
      package-lock.json
      Copy the code
    5. Use Mongoose for database connection

      Install the mongoose library

      npm install mongoose --save-dev
      Copy the code
    6. The code in db.js in the DB directory leads out the Mongoose extension module, which is used to connect to the database abnormally and disconnects

      const mongoose = require('mongoose');
      
      / / the connection
      const DB_URL = 'mongodb://localhost:27017/myBlog'
      
      mongoose.connect(DB_URL)
      
      mongoose.connection.on('connected'.function(){
          console.log('Mongoose connection open to ' + DB_URL);
      })
      
      /** * link error Database link error */
      
      mongoose.connection.on('erroe'.function(err){
          console.log('Mongoose connection disconnected');
      })
      
      /** * Disconnected The connection is disconnected */
      mongoose.connection.on('disconnected'.function(){})module.exports = mongoose 
      Copy the code
    7. Db index.js, which defines the query and save methods

      const mongoose = require('./db');
      const { model ,Schema} = require('mongoose');
      //const Schema = mongoose.Schema;
      const ceshiSchema = new Schema({
          title: String.body:String.date:Date}, {collection: 'ceshi' })
      const MyModel = mongoose.model('ceshi', ceshiSchema);
      class Mongodb {
          constructor(){}/ / query
          query () { 
              return new Promise((resolve,reject) = >{
                  MyModel.find({},(err,res) = >{
                      if (err) {
                          reject(err)
                      }
                      resolve(res)
                  })
              })
          }
          / / save
          save(obj){
              const m = new MyModel(obj)
              return new Promise((resolve,reject) = >{
                  m.save((err,res) = >{
                      if (err) {
                          reject(err)
                      }
                      resolve(res)
                      console.log(res)
                  })
              })
          }
      }
      module.exports = new Mongodb()
      Copy the code
    8. The routes/index.js interface is defined

      const ModelDb  = require('. /.. /db');
      outer.get('/mongotest'.async(ctx,next)=>{
        let data = await ModelDb.query()
        ctx.body = data
      })
      Copy the code

  • In the next chapter, WE will talk about the interface of vue request. If you don’t have enough skills, you need to work around. Just like your personality, you can go and do what you want.