The words written in the front

Hello, little friends, I am Pubdreamcc, this article is still out of my GitHub node learning tutorial, if you think pubdreamcc is still ok, I hope to give a star, thank you for your appreciation, your thumbs up is my motivation to continue to update ~

Node tutorial github

Directing a start

  • 1. Install the mongo

    Install here, I will not introduce in detail, you can choose according to the official website to match their own computer system version can be installed.

    MongoDB download address: download

    After downloading, click open direct next, next ok.

  • 2. The early experience

    1. Configuring environment Variables

    After the installation is complete, a mongoDB folder is generated under the installation directory. Open the folder, go to the bin folder, and configure the path here as environment variables.

    1. Create a storage database filedata

    Create a data directory under the root directory of any disk to store database files. MongoDB automatically sets the data folder in the root directory of the disk where the mongoDB installation location is located as the data storage directory. You can also create the folder in the drive where the mongoDB installation location is located.

    1. Starting the mongoDB Database

    If the data directory is created in the root directory of the installation location, open the command line directly and type:

     mongod
    Copy the code

    If it is another location, you need to specify the location where the data is stored:

    Mongod --dbpath File pathCopy the code

    Waiting for connections on port 27017 Waiting for connections on port 27017

    1. Connecting to a Database

    Open another command line, type mongo, and by default connect to the local open database. Ok, now that we are done with how to start a mongoDB database, we just need to save the data to the database and manipulate the data.

MongoDBConcept of analytical

As a NoSQL database, mongoDB has a very low cost for our front-end learning and will be used together with Node in the later stage. In mongoDB, key-value pairs are stored in a format similar to JSON. It is also very cool to operate, and we do not need any SQL language foundation.

There are three basic core concepts in mongodb:

  • The document

  • A collection of

  • The database

A collection can contain multiple documents, and a database can have multiple collections. Let me explain one by one:

Document: A document is a key-value pair (or BSON), essentially similar to a KEY-value pair of a JSON object.

{"name":"pubdreamcc"."age": 24}
Copy the code

Collections: Collections are groups of MongoDB documents, which are essentially arrays of objects.

For example, we could insert documents from the following different data structures into the collection:

{"name":"pubdreamcc"}
{"name":"pubdreamcc1"."name":"pubdreamcc2"}
{"name":"pubdreamcc3"."name":"pubdreamcc4"."num":5}
Copy the code

dataBase

The database concept here is the same as that of a relational database, which can contain multiple collections.

The following figure is used to show the comparison between some concepts in mongoDB and SQL concepts for understanding.

mongoDBBasic operation

Now that we have connected to our local database, from this command line, we can perform many of the basic operations mongoDB provides, such as add, delete, change, and check.

  • 1. Create a database: use the database name.

    If the database does not exist, create the database, otherwise switch to the specified database.

    The default MongoDB database is test. If you do not create a new database, the collection will be stored in test.

  • 2. Run show DBS to view all databases

  • DropDatabase: db.dropdatabase (), you can use db command to check the current database name.

  • 4. Create a collection: db.createcollection

  • 5. Check existing collections: show Collections

  • Drop (db); drop(db);

    If the selected collection is successfully deleteddrop()Method returnstrueOtherwise returnfalse.

  • Db. Set name. Insert (document). Inserts a document into the specified collection. The data structure of the document is basically the same as JSON.

  • 8. Update document: The update() method is used to update an existing document.

       db.collection.update(
         <query>,
         <update>,
         {
           upsert: <boolean>,
           multi: <boolean>,
           writeConcern: <document>
         }
       )
    Copy the code

    Parameter Description:

    • Query: The query condition is similar to where in the SQL update query.

    • updateUpdate objects and some update operators (e.gInc…). SQL update set ();

    • Upsert: Optional, this parameter means whether to insert objNew if no update record exists. True is insert, default is false, no insert.

    • Multi: Optional. By default, mongodb updates only the first found record. If this parameter is true, mongodb updates all found records.

    • WriteConcern: Optional, level of exception thrown.

  • 9. Delete documents:

    db.collection.remove(
      <query>,
      <justOne>
    )
    Copy the code

    Parameters that

    • Query :(optional) conditions for the document to be deleted.

    • JustOne: (Optional) If this parameter is set to true or 1, only one document is deleted. If this parameter is not set, or the default value false is used, all documents matching the criteria are deleted.

    • WriteConcern :(optional) level of an exception thrown.

  • Db.collection.remove ({})

  • Db.collection.find (query, projection)

    Parameters that

    • Query: Optional. Use the query operator to specify the query conditions.

    • Projection: Optional, using the projection operator to specify the key to return. Query returns all key values in the document, simply omit this parameter (the default is omitted).

    PS:

    If you need to read data in a readable way, you can use the 'pretty()' method in the following syntax: json db.col.find().pretty() 'Copy the code

    The pretty() method displays all documents in a formatted manner.

  • 12. Query a document (match condition first) : db.collection.findone ()

The Node operating mongo

  • Method one:

    Use the node mongoDB driver package provided by mongoDB. This method is officially provided. Interested students can go to NPM official website to find the documentation.

    mongoDBNPM document

  • Method 2:

    Use the mongoose

    Mongoose is an object model tool for convenient operation of mongodb in node.js environment.

    Official API documentation

Here’s how to use mongoose.

  1. Install the mongoose

    npm install mongoose
    Copy the code

    Once the installation is complete, open mongodb. To open mongodb, type: mongod

  2. Mongoose was used to connect mongodb

    Create a new JS file and introduce Mongoose. Here you can refer to a Hello World written on the official website.

    const mongoose = require('mongoose')
    // Connect to the database
    mongoose.connect('mongodb:// database address (including port number)/ database name ', (err, ret) => {
      if (err) {
        console.log('Connection failed')}else {
        console.log('Connection successful')}})Copy the code

    Now we are ready to connect to the database. Note that if you do not specify a database name, the default is to connect to the test database.

  3. Create the Schema and design the document structure

    Schema what on earth is, before we insert the data into database should design a little bit under the structure of the document, and also what is the structure of the relational database tables, there is a certain design makes the integrity of the data, no dirty data, Schema is used to do this, we look at the official introduction:

    Schema is mainly used to define the document structure in MongoDB Collection. According to Mongoose’s definition of table structure, each Schema will be mapped to a collection in mongodb. Schema does not have the ability to operate databases.

    It is easy to define a Schema by specifying the field name and type. The following eight types are supported:

    String String Number Number Date Date Buffer binary Boolean Boolean value Mixed Mixed type ObjectId ObjectId Array ArrayCopy the code

    Schema is called with Mongoose. Schema, and the new method is used to create the Schema

    / / into the Schema
    const Schema = mongoose.Schema
    // Create a Schema with new
    const userSchema = new Schema({
      // Here to design the structure of the document, each document inserted into the collection must be the structure specified below
      name: {
        type: String.required: true // specify name as a required field
      },
      password: {
        type: String.required: true
      },
      email: {
        type: String}})Copy the code

    Using the example above, we created a userSchema schema, specifying that each document must have name, password, and email fields of type String, with or without them.

  4. Publish schemas as Models

    A model is a model generated by a Schema that performs operations on a database. Each instance of a Model is a document.

    To publish a Schema as a model, simply call mongoose’s mongoose.model() method. Mongoose.model () takes two parameters, the first parameter represents the name of the model, and the second parameter is Schema, which returns the model constructor. Make sure the first parameter is set to the same value as the return value of mongoose.model(), otherwise it will fail. If the last character of the model name is a letter, it becomes plural. If the last character of the model name is a number, it remains unchanged. For example: Model name: User, the resulting set name is users, model name: User1, the resulting set name is User1. User1.

    Publish the Schema as a model
    const User = mongoose.model('User', userSchema)
    Copy the code
  5. Through the model constructor, you can perform a series of add, delete, change and query operations on the database.

    Ok, now that we have gone through the above steps, we are finally ready to manipulate the database through the User model constructor.

Mongoose add, delete and modify mongoDB

Increase the data

Instantiating a model constructor results in a concrete document.

const user = new User({
  // The specified data must be passed in the same structure as the previous Schema configuration
  name: 'pubdreamcc'.password: '123456'.email: '[email protected]' // Optional
})

// Persist data through the save() method

user.save((err, ret) = > {
  if (err) {
    console.log('Save failed')}else {
    console.log('Saved successfully')
    console.log(ret) // ret is the newly added document}})Copy the code

Ok, with the above two steps we have saved a data to the database, that’s how simple.

Query data

There are several apis for querying data. Check out the Mongoose website:

  • find()
  • findById()
  • findOne()

The specific usage is similar to that of using mongoDB data on the console. If you don’t know, check out the first section of this chapter: Using the mongoDB database

I’m going to pick a findOne representative here

User.findOne({name: 'pubdreamcc'}, (err, ret) => {
  if (err) {
    console.log('Query failed')}else {
    console.log(ret) // ret is the queried document}})Copy the code

FindOne () looks for the first document that matches, usually passing in a lookup condition (object), which in this case looks for the document whose name is Pubdreamcc from the database.

Delete the data

There are also several ways to delete data, as shown in the official API:

  • remove()
  • findOneAndRemove()
  • findByIdAndRemove()

Remove() removes all matching documents, findOneAndRemove() removes the first matching document, and findByIdAndRemove() removes a single document with a unique ID.

Here, findByIdAndRemove() is selected to illustrate. Other friends can go to the API on the Official website of Mongoose. I won’t repeat this again and again.

Mongoose official website API: API Document

User.findByIdAndRemove('id value', (err, ret) => {
  if (err) {
    console.log('Delete failed')}else {
    console.log('Deleted successfully')
    console.log(ret) // RET is the feedback object for deleting information, including several items of data deleted successfully}})Copy the code

Update the data

There are also several apis for updating data. I will list them and then select one to illustrate them. Other friends can go to the official website to check the API.

  • findByIdAndUpdate()
  • update()
  • findOneAndUpdate()

Select Update () to demonstrate:

User.update({name: 'pubdreamcc'}, {email: '[email protected]'}, (err, ret) => {
  if (err) {
    console.log('Update failed')}else {
    console.log('Update successful')}})Copy the code

The update() method will update all the data that meets the criteria, and above we have changed the email of all documents whose name is: Pubdreamcc to [email protected].

conclusion

This article is also I looked up a lot of information, including relevant tutorials, if there is a mistake in some places, friends can leave a comment.

That’s all. Thank you!