preface

If a website needs to store a large amount of information, then a database is needed. CRUD operation of database is an important operation of back-end server. In this article, we’ll talk about databases. A database is a warehouse storing data, which is organized and stored according to a certain data structure. According to the early database theory, there are three popular database models, which are hierarchical database, network database and relational database (the first two have basically disappeared). In today’s Internet, the most common Database models are RDBMS (Relational Database Management System) and non-relational Database (noSQL). Relational database, the more famous Oracle, MySQL; A non-relational database, or NoSQL, doesn’t mean “no SQL”, it means “not only SQL”, not just SQL. The full name of SQL is Structured Query Language(SQL), which is a fully functional database Language designed to create a set of commands for databases. Declarative programming, like JavaScript, is used to think about the “what “, not the” how “. Common examples of non-relational databases are Redis and MongoDB, our hero today.

mongoDB

Basic Concepts of mongoDB

MongoDB is a document-oriented database, which has three important concepts: database, collection and document.

  • Database: corresponds to a database in SQL. All data is stored in this space
  • Collection: Corresponding to SQL tabel, it represents a table/collection of data. It can be understood as a type of data stored
  • Document: Corresponding to row in SQL, represents a data record row/document, which can be understood as a stored piece of data

Obviously, there is an inclusion relationship between these three concepts, with a database containing many collections, and collections containing many documents. From the point of view of mathematical sets,A database is a collection of collections, and collections are collections of documents. Below is a visual representation of the relationship between the three.



In addition, there are three key concepts in MongoDB: field, index and primaryy key.

  • Field: If document stands for ROW in SQL, then the concept of field stands for column in SQL. Also known as a key in a key-value pair.
  • Index: This concept is known by its name
  • Primary key: unique identifier of data in the MongoDB database. The default primary key is_idfield

This concludes the basic concepts in mongoDB. Next, let’s look at a piece of data actually stored in the mongoDB database:

  • How it looks in the database:

And you can see that this piece of data, or you could say this document, has seven fields, and the primary key is_id. When the data has been queried, it is returned in the following JSON format

{
  "_id" : ObjectId("60d571d606d8634c18cf2338"),
  "agreeArticle": []."username" : "ggg"."password" : "202cb962ac59075b964b07152d234b70"."type" : "normal"."agreeCount" : 0."__v" : 0
}
Copy the code

use

In javascript, the use of mongoDB is mainly realized through the intermediate library Mongoose. As a result, many operations are simply called mongoose, which will be described in the next section. Here, the CRUD(add, delete, change and check) operations of documents in mongoDB are mainly introduced. The existing database and collection elements should be in place before performing CRUD operations on the document. Before doing anything else, install and start mongoDB, and establish connections to the database

Install and start mongoDB

  • Install and start the mongo, please stamp the following link: www.runoob.com/mongodb/mon…
  • Mongo start the database service, please stamp the following link: www.runoob.com/mongodb/mon…

The database

The key commands for database operations are as follows:

  • Create database:use DATABASE_NAME
  • Display database list:show dbs
  • Display current database:db
  • Delete database:db.dropDatabase()

Note: Use caution when deleting a database!!

A collection of

A few key commands for collection operations are as follows:

  • Create a collection:db.createCollection("COLLECTION_NAME")
  • Display the collection in the current database:show collections
  • Delete collection:db.COLLECTION_NAME.drop()

The document

  • Increasing (create) :

    In mongoDB, we need to insert the Document into the collection. The data structure of each document is basically the same as JSON. However, this data structure is not called JSON in mongoDB, but BSON, short for Binary JSON. Next, let’s focus on the syntax for inserting a document into a collection.
    • db.COLLECTION_NAME.insert(document): Will be thrown if the primary key of the inserted data already existsorg.springframework.dao.DuplicateKeyExceptionThe primary key is repeated and the current data is not saved
    • db.COLLECTION_NAME.save(document)If:_idThe data is updated if the primary key exists, or inserted if it does not. This method is deprecated in the new version and can be useddb.collection.insertOne()ordb.collection.replaceOne()Instead.
    • db.COLLECTION_NAME.insertOne(<document>,{writeConcern:<document>}): Insert method added after version 3.2. Among them,<document>Represents the document to be written;writeConcernIndicates the write policy. The default value is 1, indicating that the write operation is required. 0 indicates that no write operation is required.
    • db.COLLECTION_NAME.insertMany([<document 1>, <document 2>, ... ] ,{writeConcern: <document>, orderd: <boolean>}): Insert method added after version 3.2. Among them,<document>andwriteConcernThe meaning is the same as before,orderedIndicates whether to write data in sequence. The default value istrue, write in order.

The meaning of the writeConcern field is described in the documentation as follows: Write concern describes the level of acknowledgment requested from MongoDB for write operations to a standalone mongod or to replica sets or to sharded clusters. In sharded clusters, mongos instances will pass the write concern on to the shards.

Write Concern contains the following fields:

{
    w: <value>,           
    j: <boolean>,
    wtimeout: <number>
}
Copy the code

Details please refer to the related documents, document links as follows: docs.mongodb.com/manual/refe…

  • Delete (delete)

    The syntax for deleting documents is as follows:
    db.collection.remove(
        <query>,
        {
            justOne: <boolean>,
            writeConcern: <document>})Copy the code
    • <query>: Indicates the conditions for deleting a document. This parameter is optional
    • justOne: This parameter is optional if set toTrue or 1, only one document is deleted; If this parameter is not specified, use the default valuefalse, delete all documents that match the condition.
    • writeConcern: Optional parameter, indicating the level of exception thrown.
  • The syntax for updating a document is as follows:
    db.collection.update(
        <query>,
        <update>,
        {
            upsert: <boolean>,
            multi: <boolean>,
            writeConcern: <document>})Copy the code
    • query: Update query conditions
    • updateUpdate object and some update operators
    • upsert: Specifies whether to insert objNew if no update record exists. The default value is true and false.
    • multi: This parameter is optional. The default value is false and only the first record found is updated. If set to true, all eligible data is updated
    • writeConcern: Optional parameter, indicating the level of exception thrown
  • Lookup (Retrieve) mongoDB’s query operation can be referenced in the following article, which will not be described here: juejin.cn/post/684490…

mongoose

Mongoose is an open source library that uses nodeJS to manipulate mongoDB databases. Mongoose encapsulates the operation of connecting database, creating collection and Document CRUD.

Install the mongoose

Run in your own project: NPM install Mongoose –save

Connecting to a Database

No more nonsense, direct paste code:

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/test',
            {useNewUrlParser: true.useUnifiedTopology: true})
const db = mongoose.connection;
db.on('open'.function() {
  // The database successfully connected callback function
});
Copy the code

Schema and the Model

In Mongoose, Schema is the starting point, which corresponds to the collection in mongoDB and defines the data structure of each document in the collection. Here is an example of a Schema:

import mongoose from 'mongoose';
const { Schema } = mongoose;

const blogSchema = new Schema({
    title:  String.// String is shorthand for {type: String}
    author: String.body:   String.comments: [{ body: String.date: Date}].date: { type: Date.default: Date.now },
    hidden: Boolean.meta: {
      votes: Number.favs:  Number}});Copy the code

In this code, the blogSchema fields are specified, along with the data type of each field. In mongoDB, collection is a collection of Document, while Schema corresponds to mongoDB collection. So, another concept that corresponds to document is model. An instance of a Model is a document. Therefore, the addition, deletion, modification and check of data in mongoDB database are all carried out by Model in Mongoose. The first step in using model is to call the Mongoose. model method:

const Blog = mongoose.model('Blog',blogSchema)
Copy the code

As you can easily see, this method takes in two parameters, the name of the collection and the Schema object. After calling this method, we can add, delete, alter, and query the data:

  • increase

    To add data to a database, you first need to instantiate onemodelObject, which is easy to understand. To add data to a database, you need data in the first place. Then, callmodel.save()Method can. Examples are as follows:
    new Blog({
        title:  'xxx'.// String is shorthand for {type: String}
        author: 'xxx'.body:   'xxx'.comments: [].date: Date.now,
        hidden: true.meta: {
          votes: 0.favs:  0
        }
    }).save((err) = > {
        // This is a callback function that handles the operation after the data is saved
    })
    Copy the code

    model.save()It returns onepromiseObject. Therefore, the callback function can also be in the form of a chain call.

  • delete

    The delete operation has two methods to call:deleteOne()anddeleteMany(). With both methods, you need to pass in a condition for the data to be deleted
    Tank.deleteOne({ size: 'large' }, function (err) {
      if (err) return handleError(err);
      // deleted at most one tank document
    });
    Copy the code

    You can also useModel.findOneAndDelete(), using the same method as before

  • change

    The data update operation can take the following methods:
    • Model.findOneAndUpdate()
    • Model.update()
    • Model.updateMany()
    • Model.updateOne()

    The required parameters are as follows:

    • Conditions: Filter criteria for the data to be updated
    • Update: big data after update
    • Options: Optional parameters, some configuration options for this method
    • Callback: a callback after the update operation has been performed. Note that the callback has two parameters, err and data. Data refers to the original data, not the updated data.
  • check

    The following methods can be used to query data in a database:
    • Model.find()
    • Model.findOne()
    • Model.findMany()

    All that is required is that the update operation removes the second parameter and everything else is the same.

Query

There are many features of Query objects. However, it doesn’t seem to work very well in simple applications. However, you can use it as a promise object. Of course, you can use it that way, but remember there’s a difference.

The words in the back

This article is a summary of some content after I used mongoDB and Mongoose for my first project, so the principle is enough. Obviously, they have many, many more important features. If necessary, you must refer to the official documentation. Official Document Archive:

  • MongoDB Official Documentation
  • Mongoose official documentation
  • MongoDB Tutorial