Using mongoose to operate the database in Mongodb and node.js

Directory

1. lowdb

2. What is MongoDB?

3. Mongodb core concepts

4. Download and use of Mongodb

5. Database and collection commands

5.1. Database commands

5.2. Collection command

5.3. Document commands

6. Mongoose

6.1. Insert document

6.2. Field type

6.3. Field value verification

6.3.1. Required items

6.3.2.Default value

6.3.3. Enumeration value

6.3.4. Unique value

6.4. Delete documents

6.5. Update documentation

6.6. Query documents

6.7. Condition control

6.7.1. Operators

6.7.2. Logical operations

6.7.3, regular matching

6.8. Mongoose personalized reading

6.7.1. Field screening

6.7.2. Data sorting

6.7.3. Data interception

7. Mongodb graphical management tool

7.1, robo3t

7.2、Navicat


1, lowdb

A simple third-party database library that uses JSON files to save data and perform additions, deletions, modifications, and queries.

It can be used when there is no database or the amount of data is too small to use the database, just understand it.

2. What is Mongodb?

MongoDB is a database based on distributed file storage.

Compared with pure file management data, database management data has the following characteristics:

  • faster
  • more scalable
  • more secure

Why choose Mongodb, because its operation syntax is similar to JS, easy to use, and low learning cost.

3. Mongodb core concept

  • Database (database) The database is a data warehouse. Many databases can be created under the database service, and many collections can be stored in the database.
  • A collection (collection) is similar to an array in JS, and many documents can be stored in the collection.
  • Document (document) The document is the smallest unit in the database, similar to the object in JS.

4. Mongodb download and use

Download address: Download MongoDB Community Server | MongoDB

It is recommended to choose the zip type, which is more versatile.

The configuration steps are as follows:

  • Move the compressed package to C:\Program Files, and then unzip it
  • Create the C:\data\db directory, mongodb will store the data here
  • Start the command line with the bin directory in mongodb as the working directory.
  • run mongod.exe

Seeing waiting for connections indicates that the service started successfully.

client program

  • run mongo.exe

Notice:

  • For the convenience of subsequent use of the mongod command, you can configure the bin directory to the environment variable path
  • Do not select the content of the server window, the selection will stop the service, you can press Enter to cancel the selection

5, Database and Collection Command

5.1, database command

  • 1. Display all databases
    • show dbs
  • 2. Switch to the specified database
    • use database name
  • 3. Display the current database
    • db
  • 4. Delete the current database
    • use library name
    • db.dropDatabase()

5.2, collection command

  • 1. Create a collection
    • db.createCollection(‘collection name’)
  • 2. Display all collections in the current database
    • show collections
  • 3. Delete a collection
    • db.collectionname.drop()
  • 4. Rename the collection
    • db.Collection name.renameCollection(‘newName’)

5.3. Document Command

  • 1. Insert document
    • db.Collection name.insert(document object)
  • 2. Query documents
    • db.Collection name.find({age: 20}) // Find documents whose age is 20. Find does not pass parameters and queries all documents.
  • 3. Update documents
    • db.Collection name.update (query conditions, new document) // Without $set, the entire document will be replaced
    • db.Set name.update({name: ‘Zhang San’}, {$set:{age:19}}) // If $set is used, only age is modified
  • 4. Delete documents
    • db.Collection name.remove(query condition)

6. Mongoose

Mongoose is an object document model library.

It is convenient for us to use code to operate the mongodb database.

npm i mongoose@6
//Import mongoose
const mongoose = require('mongoose');

// Connect to mongoose service
mongoose.connect('mongodb://127.0.0.1:27017/bilibili'); // If the bilibili database does not exist, it will be automatically created

//Set callback
mongoose.connection.on('open', () => {
    console.log('Connection successful');
}); // Connection success callback
mongoose.connection.on('error', () => {
    console.log('Connection failed');
}); // Connection failure callback
mongoose.connection.on('close', () => {
    console.log('Connection closed');
}); // Connection close callback

//Close the mongodb connection
setTimeout(() => {
    mongoose.disconnect();
}, 3000);

6.1. Insert document

//Import mongoose
const mongoose = require('mongoose');

// Connect to mongoose service
mongoose.connect('mongodb://127.0.0.1:27017/bilibili'); // If the bilibili database does not exist, it will be automatically created

//Set callback
mongoose.connection.on('open', () => {
    //Create the structure object of the document, set the attributes of the documents in the collection and the type of attribute values
    let BookSchema = new mongoose.Schema({
        name: String,
        author: String,
        price:Number
    });

    //Create a model object, an encapsulation object for document operations
    let BookModel = mongoose.model('book', BookSchema);

    //Add
    // BookModel.create({
    // name: 'Journey to the West',
    // author: 'Wu Chengen',
    // price: 19.9
    // }, (err,data) => {
    // if (err) {
    // console.log(err);
    // return;
    // }
    // // If there is no error, output the inserted document object
    // console.log(data);
    // });

    // add multiple
    BookModel.insertMany([{
        name: 'Journey to the West',
        author: 'Wu Chengen',
        price: 19.9
    },{
        name: 'Journey to the West',
        author: 'Wu Chengen',
        price: 19.9
    },{
        name: 'Journey to the West',
        author: 'Wu Chengen',
        price: 19.9
    }], (err, data) => {
        if (err) {
            console. log(err);
            return;
        }
        // If there is no error, output the inserted document object
        console. log(data);
    });
}); // Connection success callback
mongoose.connection.on('error', () => {
    console.log('connection failed');
}); // Connection failure callback
mongoose.connection.on('close', () => {
    console.log('connection closed');
}); // connection close callback

6.2, Field Type

String: String

Number: number

Boolean: Boolean value

Array: array

Date: date

Buffer: Buffer object

Mixed: Any type, which needs to be specified using mongoose.Schema.Types.Mixed

ObjectId: Object ID, which needs to be specified using mongoose.Schema.Types.ObjectId

Decimal128: High-precision numbers, which need to be specified using mongoose.Schema.Types.Decimal128

6.3, field value verification

6.3.1, required items

title: {
  type: String,
  required: true
}

6.3.2, default value

author: {
  type: String,
  default: 'anonymous'
}

6.3.3, enumeration value

sex: {
  type: String,
  enum: ['male', 'female']
}

6.3.4, unique value

username: {
  type: String,
  unique: true,
}

Unique needs to rebuild the collection to be effective. Never trust user input.

6.4, delete document

//Import mongoose
const mongoose = require('mongoose');

// Connect to mongoose service
mongoose.connect('mongodb://127.0.0.1:27017/bilibili'); // If the bilibili database does not exist, it will be created automatically

//Set callback
mongoose.connection.on('open', () => {
    // Create the structure object of the document, set the properties of the document in the collection and the type of the property value
    let BookSchema = new mongoose.Schema({
        name: String,
        author: String,
        price:Number
    });

    // Create a model object, the encapsulation object for document operations
    let BookModel = mongoose. model('book', BookSchema);

    // Delete one
    BookModel.deleteOne({_id: '6461be48670777b4e3f2bfcc'}, (err, data) => {
        if (err) {
            console.log(err);
            return;
        }
        console. log(data);
    });
    // batch deletion
    BookModel.deleteMany({is_hot: false}, (err, data) => {
        if (err) {
            console.log(err);
            return;
        }
        console. log(data);
    });

}); // Connection success callback
mongoose.connection.on('error', () => {
    console.log('Connection failed');
}); // Connection failure callback
mongoose.connection.on('close', () => {
    console.log('Connection closed');
}); // Connection close callback

6.5, update document

//Import mongoose
const mongoose = require('mongoose');

// Connect to mongoose service
mongoose.connect('mongodb://127.0.0.1:27017/bilibili'); // If the bilibili database does not exist, it will be automatically created

// set callback
mongoose.connection.on('open', () => {
    //Create the structure object of the document, set the attributes of the documents in the collection and the type of attribute values
    let BookSchema = new mongoose.Schema({
        name: String,
        author: String,
        price: Number
    });

    //Create a model object, an encapsulation object for document operations
    let BookModel = mongoose.model('book', BookSchema);

    // update one
    // BookModel.updateOne({name: 'Journey to the West'}, {price: 9.9}, (err,data) => {
    // // judge err
    // if (err) {
    // console.log('Update failed');
    // return;
    // }
    // console.log(data);
    // });

    // batch update
    BookModel.updateMany({name: 'Journey to the West'}, {price: 9.9}, (err,data) => {
        // judge err
        if (err) {
            console.log('Update failed');
            return;
        }
        console. log(data);
    });

}); // Connection success callback
mongoose.connection.on('error', () => {
    console.log('Connection failed');
}); // Connection failure callback
mongoose.connection.on('close', () => {
    console.log('Connection closed');
}); // Connection close callback

6.6. Query Documents

// import mongoose
const mongoose = require('mongoose');

// connect mongoose service
mongoose.connect('mongodb://127.0.0.1:27017/bilibili'); // If the bilibili database does not exist, it will be automatically created

// set callback
mongoose.connection.on('open', () => {
    //Create the structure object of the document, set the attributes of the documents in the collection and the type of attribute values
    let BookSchema = new mongoose.Schema({
        name: String,
        author: String,
        price: Number
    });

    //Create a model object, an encapsulation object for document operations
    let BookModel = mongoose.model('book', BookSchema);

    // Query single item
    BookModel.findOne({name: 'Journey to the West'}, (err, data) => {
        if (err) {
            console.log(err);
            return;
        }
        console. log(data);
    });

    // Get the document based on ID
    BookModel.findById('6461c222f73d78ca0b9fd980', (err, data) => {
        if (err) {
            console.log(err);
            return;
        }
        console. log(data);
    });

    // Batch acquisition (conditional)
    BookModel.find({author: 'Wu Chengen'}, (err, data) => {
        if (err) {
            console.log(err);
            return;
        }
        console. log(data);
    });

    // Unconditional, read all
    BookModel.find((err, data) => {
        if (err) {
            console.log(err);
            return;
        }
        console. log(data);
    });

}); // Connection success callback
mongoose.connection.on('error', () => {
    console.log('connection failed');
}); // Connection failure callback
mongoose.connection.on('close', () => {
    console.log('connection closed');
}); // connection close callback

6.7, Conditional Control

6.7.1, Operator

In mongodb, operators such as >< cannot be used, and alternative symbols must be used:

  • >,$gt
  • <,$lt
  • >=,$gte
  • <\,$lte
  • !==,$ne
db.students.find({id:{$gt:3}}); All documents with ID number greater than 3

6.7.2, Logical Operation

$or logical OR case

db.students.find({$or:[{age:18}, {age:24}]});

$and logical AND situation

db.students.find({$and:[{age:18}, {age:24}]});

6.7.3, Regular Match

The regular syntax of JS can be used directly in the conditions, and fuzzy queries can be performed:

db.students.find({name:/imissyou/});

6.8, mongoose personalized reading

6.7.1, Field Filtering

SongModel.find().select({_id:0, title:1}).exec(function(err, data) {
  if (err) throw err;
  console. log(data);
  mongoose.connection.close();
})

6.7.2, Data Sorting

SongModel.find().sort({hot:1}).exec(function(err, data) {
  if (err) throw err;
  console. log(data);
  mongoose.connection.close();
})

6.7.3, Data Interception

// skip skip, limit limit
SongModel.find().skip(10).limit(10).exec(function(err, data) {
  if (err) throw err;
  console. log(data);
  mongoose.connection.close();
})

7. mongodb graphical management tool

7.1, robo3t

Go to github to download, free

7.2, Navicat

TOLL

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge MySQL entry skill treeHome pageOverview 65807 people are studying systematically