[Mongo] connect Mongo database (1 / 3)

Time:2021-1-20

The command line enters the Mongo database
mongo

View all databases
show dbs

New (or existing) fruit data table and new data
db.fruits.save({name: ‘apple’, price: 5});

lookup
db.fruits.find({price: 5})

View all the tables in the database
db.getCollectionNames()

Connection Mongo database operation

conf.js
module.exports = {
    url: 'mongodb://127.0.0.1:27017',
    dbName: 'local',
}
db.js
const conf = require('./conf');
Const {EventEmitter} = require ('events'); // database asynchronous connection tool

//Client
const { MongoClient } = require('mongodb');
class Mongodb {
    constructor(conf) {
        this.conf = conf;
        this.emmiter = new EventEmitter();
        //Connection
        this.client = new MongoClient(conf.url, {
            useNewUrlParser: true,
        })

        this.client.connect(err => {
            console.log(err);
            if (err) {
                throw err;
            }
            console.log ('normal connection ');
            this.emmiter.emit('connect')
        })
    }
    col(colName, dbName = conf.dbName) {
        return this.client.db(dbName).collection(colName);
    }

    once(event, cb) {
        this.emmiter.once(event, cb)
    }
}
module.exports = new Mongodb(conf)
initData.js
const mongodb = require('./models/db');
mongodb.once('connect', async () => {
    const col = mongodb.col('fruits');
    //Delete existing data
    await col.deleteMany();
    const data = new Array(100).fill().map((value, index) => {
        return {
            name: 'XXXX' + index,
            price: index,
            category:  Math.random () > 0.5? 'vegetable':'fruit ',
        }
    })
   
    await col.insertMany(data);
    console.log ('Insert test data successfully ');
    
})

API usage

(async () => {
    const {MongoClient: MongoDB} = require('mongodb');
   
    //Create client
    const client = new MongoDB(
        'mongodb://localhost:27017', 
        {
            useNewUrlParser: true,
        }
    )
   
    let ret;
    //Create a connection
    ret = await client.connect();
    console.log('connect: ', ret);
   
    const db = client.db('local');
    const fruits = db.collection('fruits')
    
    //Delete
    ret = await fruits.deleteMany();
    
    //Add document
    ret = await fruits.insertOne({
        name: 'mango',
        price: 20.1
    })
    console.log ('Insert successfully ', ret.ops )
   
    //Inquiry
    ret = await fruits.findOne({
        name: 'mango'
    })
    console.log ('query ', RET)

    //Update
    ret = await fruits.updateOne({
        name: 'mango'
    }, {
        $set: {
            name: 'apple'
        }
    })
    console.log ('update ', JSON.stringify (ret))
})()