8. Use MongoDB in Node.js

1. The basic perception of MongoDB

MongoDBIt is a non-relational database, no need to design tables, each table is a collection concept. After installation MongoDB, open the terminal command line and enter the command to mongoconnect to the database, and you can use MongoDBsome commands under the command line : the connection is successful
Insert picture description here
as shown in the figure MongoDB.
MongoDBSome basic commands:

  1. show dbs View all databasesList item

  1. use 数据库名称 Switch to the specified database (it will be created if it does not exist). Show dbs will be displayed after inserting data.
  2. Insert db.students.insertOne({"name": "counterrr"})data .
  3. Check all the collections under the current data show collections.
  4. db.students.find()Find out studentsall the data under the collection.
    Insert picture description here

2. Use MongoDB in Node.js

Use MongoDBofficial packages mongodb, official documents .
But we generally don't use this package for real development. Generally, a third party is mongooseused for operation MongoDB, and the third-party package is packaged based on the official mongodbpackage. Next, we will mongoosedo the following based on demo:

  1. Create a file on the desktop mogoose-demo, and then drag this folder to the vscodeeditor.
  2. Then open vscodethe terminal command line, enter the command to npm init -yquickly generate the project specification.
  3. Enter the command again npm install mongoose. Install mongoosethis package.
  4. Create in the root directory db.js, enter the code:
    // 引入mongoose
    const mongoose = require('mongoose');
    // 连接MongoDB数据库
    mongoose.connect('mongodb://localhost:27017/test', {
          
          useNewUrlParser: true, 	useUnifiedTopology: true});
    // 创建模型,Cat这个模型它会自动生成一个cats集合,里面有name这个属性,并且是String类型的
    const Cat = mongoose.model('Cat', {
          
           name: String });
    //  实例化一个Cat
    const kitty = new Cat({
          
           name: 'Zildjian' });
    // 持久化保存
    kitty.save().then(() => console.log('meow'));
    
    Then we run it and enter it in the command node db.jsas follows:
    Insert picture description here
    successfully printed out. Then we went to the terminal command line to check:
    Insert picture description here
    found that there is data. Next, I loop it to generate 100 data and insert them into the database, the code is as follows:
 // 引入mongoose
 const mongoose = require('mongoose');
 // 连接MongoDB数据库
 mongoose.connect('mongodb://localhost:27017/test', {
    
    useNewUrlParser: true, 	useUnifiedTopology: true});
 // 创建模型,Cat这个模型它会自动生成一个cats集合,里面有name这个属性,并且是String类型的
 const Cat = mongoose.model('Cat', {
    
     name: String });
for(let i = 0; i < 100; i++) {
    
    
    //  实例化一个Cat
    const kitty = new Cat({
    
     name: '喵喵' + i });
    // 持久化保存
    kitty.save().then(() => console.log('meow'));
}

Open the terminal to view: the
Insert picture description here
whole process is completely similar to the javascriptsyntax. Very flexible, there are not so many rules and regulations to change.


Next, we create in the root directory db2.jsto practice the collection structure, the code is as follows:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost:27017/test', {
    
    useNewUrlParser: true, 	useUnifiedTopology: true});

var userSchema = new Schema({
    
    
    name: {
    
    
        type: String,
        required: true
    },
    password: {
    
    
        type: String,
        required: true
    }
});

// 模型构造函数
const User = mongoose.model('User', userSchema);

  • In this jsdocument, we have added Schema, that this is to set the framework of this collection, for example, nameand the passwordfield is the Stringtype of and is a must, and finally we publish this model constructor Modelto User, but MongoDBwill automatically generate usersa set of upper case to lower case , The form of singular variable plural form generates a set. Open another terminal command and enter the command mongodto connect to the database. Success as shown below:
    Insert picture description here

    Next, we will add, delete, modify and check on this basis:
    -Add:
    (Add the following code to the original code)

    // 创造实例
    const user = new User({
          
          
    name: 'Counterrr',
    password: 'mongodb'
    })
    // 存储实例
    user.save().then((data) => {
          
          
    	console.log('存储成功')
    	console.log(data)
    }, () => {
          
          
    	console.log('存储失败')
    })
    

    Then enter the command line node db2.js:
    Insert picture description here
    we can see that the successful return parameter is the current data.
    -Check:
    We commented out the added code, and then added the following code on the original basis:

    	// 查询所有
    User.find((err, res) => {
          
          
    if (err) {
          
          
        console.log('查询失败')
    }
    else {
          
          
        console.log('查询成功')
        console.log(res)
    }
    })
    

    Rerun node db2.js:
    Insert picture description here
    You can see that the query is successful. You can also query based on conditions, we insert another piece of data:

    	// 创造实例
    const user = new User({
          
          
    name: '小红',
    password: 'mongodb'
    })
    // 存储实例
    user.save().then((data) => {
          
          
    console.log('存储成功')
    console.log(data)
    }, () => {
          
          
    console.log('存储失败')
    })
    

    You can see that we inserted another piece of data, and then we commented out the code that stores Xiaohong above, and then we need to find out this piece of data named Xiaohong. The conditions are as follows:

    // 查询小红
    User.find({
          
          
     name: '小红'
    }, (err, res) => {
          
          
    if (err) {
          
          
        console.log('查询失败')
    	}
    else {
          
          
        console.log('查询成功')
        console.log(res)
     }
    })
    

    Re-run node db2.js, the effect is as follows:
    Insert picture description here
    we can see that we have followed a condition {name: '小红'}, in this case, Xiaohong will be queried.
    -Delete:
    We comment out the query code and enter the deleted code:

    User.deleteOne({
          
          
    name: '小红'
    }).then((data) => {
          
          
    console.log('删除成功')
    console.log(data)
    }, (err) => {
          
          
    console.log('删除失败')
    console.log(err)
    })
    

    Check the effect:
    Insert picture description here
    You can see that we are deleted successfully.
    -Update:
    Comment the delete code, enter the update code as follows:

    User.updateOne({
          
          
    	name: 'Counterrr'
    }, {
          
          name: 'Counter'}).then((data) => {
          
          
    	console.log('更新成功')
    	console.log(data)
    }, (err) => {
          
          
     	console.log('更新失败')
     	console.log(err)
    })
    

    We nameas Counterrrupdated Counterrras:
    Insert picture description here
    go to the query:
    Insert picture description here
    has been changed.
    More MongoDB CRUD interfaces Click for
    good later we will use MongoDBto write before our next student to re-reconstruction system. deepen impression.

Guess you like

Origin blog.csdn.net/weixin_44103733/article/details/106006003