In this paper, an object todo object (with attribute {id, name}) will be stored in Mongodb to test query deletion (Create Remove Delete = CRD). This test includes using Mongodb Shell, classically styled access code using CallBack, and modern styled code using Await/Async. Once this verification is complete, you can master the most preliminary Mongodb.

The Nodejs I use is 10.7. The operating system is Mac OS X High Sierra.

Prepare the environment

Install and run the Mongodb Daemon

brew install mongodb
mongodb
Copy the code

Access authentication

First execute Mongodb Shell:

mongo
Copy the code

Enter the command to query the database list:

> show dbs
local           0.000GB
Copy the code

Create a database

use todos
Copy the code

(If a database does not exist, it will be created. If you exit the database without performing any operations, MongoDB will delete the database.)

db.todos.insert({id:1,name:"reco"})
db.todos.insert({id:2,name:"rita"})
Copy the code

Query:

db.todos.find()

{ "_id" : ObjectId("5b727c0846b6c71a98d3af52"), "id" : 1, "name" : "reco" }
{ "_id" : ObjectId("5b727c7046b6c71a98d3af53"), "id" : 2, "name" : "reta" }
Copy the code

Delete records:

db.todo.remove({id:1})
Copy the code

Deleting a Database

db.todo.drop()
Copy the code

Use nodeJS to access Mongodb

Perform shell-like CRD on an object using nodeJS as follows:

var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/todos"; MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("Database created!" ); var dbo = db.db("todos"); // var myobj = { id: 1, name: "reco" }; // dbo.collection("todo").insertOne(myobj, function(err, res) { // if (err) throw err; // console.log("1 document inserted"); // db.close(); / /}); var myobj = [ { id: 1, name: 'reco'}, { id: 2, name: 'rita'}, ]; dbo.collection("todo").insertMany(myobj, function(err, res) { if (err) throw err; console.log("Number of documents inserted: " + res.insertedCount); dbo.collection("todo").find({}).toArray(function(err, result) { if (err) throw err; console.log(result); var myquery = { id: 1 }; dbo.collection("todo").deleteMany(myquery, function(err, obj) { if (err) throw err; console.log("document deleted"); db.close(); }); }); }); })Copy the code

The code is very simple and requires no further explanation. This code uses the mongodb module and needs to be installed first:

npm init -y
npm i mongodb --save
Copy the code

Then run it with Node index.js to see the result:

Database created!
Number of documents inserted: 2
[ { _id: 5b72ab9e3245f169ef5f43d2, id: 1, name: 'reco' },
  { _id: 5b72ab9e3245f169ef5f43d3, id: 2, name: 'rita' } ]
document deleted
Copy the code

Take advantage of advanced asynchronous features

Use Await/Async features to reduce callback hell in code. For the same function, you can use code like this:

const MongoClient = require('mongodb').MongoClient;
const connectionString = 'mongodb://localhost:27017';
(async () => {
    const client = await MongoClient.connect(connectionString,
        { useNewUrlParser: true });
    const dbo = client.db('todos');
    try {
       var res = await dbo.collection('todo').insertMany(
       	[{id:1,name:"reco"}, {id:2,name:"rita"}]);
       console.log("Number of documents inserted: " + res.insertedCount);
       var r = await dbo.collection("todo").find().toArray()
       console.log(r);
       var myquery = { id: 1 };
	   var r = await dbo.collection("todo").deleteMany(myquery)
	   console.log("document deleted");
    }
    finally {
        client.close();
    }
})().catch(err => console.error(err));
Copy the code

Executing this code produces the following output:

Number of documents inserted: 2
[ { _id: 5b72ae8a1c674a6ac1c5aa6e, id: 1, name: 'reco' },
  { _id: 5b72ae8a1c674a6ac1c5aa6f, id: 2, name: 'rita' } ]
document deletedCopy the code