nodejs - MongoDB

1. Overview of database structures and environment

1.1 Why use a database

  • Dynamic Data Web site are stored in the database
  • Persistent user database can be used to store client information collected through Form
  • Database software itself can be made efficient management of data

http://localhost/article?id=1

http://localhost/article?id=2

Processing the request by passing different parameters, the results show different data

1.2 What is a database

That database for storing data warehouse, data can be orderly storage of different categories. It is independent of the language of the software, you can manipulate it to go through the API.

Common database software: mysql, mongoDB, oracle.

nodejs can use multiple databases, using this mongoDB as a database, because mongoDB open api is JavaScript syntax is the same for nodejs, data storage is mongoDB JSON format for learning mongoDB nodejs more friendly.

1.3 MongoDB database to download and install

Download: https://www.mongodb.com/download-center/community

1.4 MongoDB visualization software

MongoDB visualization software, one way is to use graphical interface database operation.

1.5 database concepts

In one software database can contain multiple data warehouse may comprise a plurality of sets of data in each data warehouse, each data set may comprise a plurality of documents (specific data).

the term explain
database Database, mongoDB database software can create multiple databases
collection Collection, a collection of data, can be understood as an array in JavaScript
document Documents, a specific data, can be understood as an object in JavaScript
field Field, the document property name can be understood as an object property in JavaScript

1.6 Mongoose third-party packages

  • MongoDB database operations using Node.js Node.js need to rely on third-party packages mongoose

  • Use npm install mongoose command to download

1.7 start MongoDB

Run in command-line tool net start mongoDB to start MongoDB, otherwise MongoDB will not connect.

Stop the service: net stop mongoDB

Note: If you deny access occurs, access is not enough, open a command-line tool with the administrative mode

1.8 Database Connectivity

Use provided mongoose connect to the database connection method.

//引入mongoose模块
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground')
     .then(() => console.log('数据库连接成功'))
     .catch(err => console.log('数据库连接失败', err));

Description:

  1. In MongoDB does not need to explicitly create a database , if you are using the database does not exist, MongoDB will be created automatically .

  2. Using the current connection will display an error warning:

    (node:9688) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
    (node:9688) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

    Two words probably meant: the current URL string analyzer discovery and monitoring engine is deprecated and will be removed in a future version of the current server.

Add the following parameters to resolve an error warning in connection method:

//引入mongoose模块
const mongoose = require('mongoose');
 mongoose.connect('mongodb://localhost/playground',{ useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log(err, '数据库连接失败'));

2. MongoDB CRUD operations

Create Collection 2.1

Creating a collection is divided into two steps, first Dui the collection set rules , and second, to create a collection instance, create mongoose.Schema constructor to create a collection.

 //创建集合规则   
const courseSchema = new mongoose.Schema({
    name:String,
    author:String,
    isPublished:Boolean
});

//创建集合并应用规则
const Course = mongoose.model('Course',courseSchema);//courses
  1. Standardize the collection name first letter capitalized, such as: Course
  2. Mongoose collection created automatically capitalize the first letter does not exist in the form of, but behind lowercase letters plus s, such as: courses
  3. modelMethod returns a constructor function, which represents a collection constructor
  4. The default will not immediately create a collection created, it is automatically created is empty but data is inserted.

2.2 Create documents

Create a document actually insert data into the collection .

In two steps:

  1. Create a collection instance.

  2. save method calls under an object instance to save data to the database.

//创建集合实例
const course = new Course({
    name:'NodeJs精品课',
    author:'Mr li',
    isPublished:true
});
//将数据保存到数据库
course.save();

Another way (with callbacks):

Course.create({name: 'JavaScript基础', author: 'Mr li', isPublish: true}, (err, doc) => { 
     //  错误对象
    console.log(err)
     //  当前插入的文档
    console.log(doc)
});

or

Course.create({name: 'JavaScript基础', author: '黑马讲师', isPublish: true})
      .then(doc => console.log(doc))
      .catch(err => console.log(err))

Note: All operations are asynchronous database operations

3.3 mongoDB data into the database

Mongodb find the installation directory database, the installation bin directory under the directory placed in an environment variable.

mongoimport –d 数据库名称 –c 集合名称 –-file 要导入的数据文件

3.4 query document

//  根据条件查找文档(条件为空则查找所有文档)
Course.find().then(result => console.log(result))

Return data:

[
  {
    _id: 5e70cd0fa25bbf21c0077aca,
    name: 'NodeJs精品课',
    author: 'Mr li',
    isPublished: true,
    __v: 0
  },
  {
    _id: 5e70cf6b0e954a332c9810a2,
    name: 'JavaScript基础',
    author: 'Mr li',
    isPublished: true,
    __v: 0
  }
]
//查找指定Id的数据
Course.find({_id: '5e70cf6b0e954a332c9810a2'}).then(result => console.log(result));

Return data

[
  {
    _id: 5e70cf6b0e954a332c9810a2,
    name: 'JavaScript基础',
    author: 'Mr li',
    isPublished: true,
    __v: 0
  }
]

Use find ways to find data no matter how many are returned array format, 0 returns an empty array

//  根据条件查找文档
Course.findOne({_id: '5e70cf6b0e954a332c9810a2'}).then(result => console.log(result))

Return data

  {
    _id: 5e70cf6b0e954a332c9810a2,
    name: 'JavaScript基础',
    author: 'Mr li',
    isPublished: true,
    __v: 0
  }

findOne method simply returns a data object format is json

//匹配大于 小于
User.find({age:{$gt:20,$lt:50}}).then(result=>console.log(result));

//匹配包含
User.find({hobbies:{$in:'敲代码'}}).then(result=>console.log(result));

//选择要查询的字段
User.find().select('name age').then(result=>console.log(result));
//注意:默认还会有_id,如果不想显示某个字段可以添加-,表示过滤字段,如:-_id

//将数据按照年龄进行排序,升序
User.find().sort('age').then(result=>console.log(result));
//说明:降序在字段前面加-,如:-age

//skip 跳过多少条数据  limit 限制查询数量
User.find().skip(3).limit(3).then(result=>console.log(result));

3.5 Delete Document

//删除查找第一个对象,并返回删除的对象
User.findOneAndDelete({}).then(result=>console.log(result));
//删除多个,条件为空删除全部,返回删除结果与个数
User.deleteMany({}).then(result=>console.log(result));

3.6 update document

// 更新单个
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))

// 更新多个
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))

3.7 mongoose verification

When you create a set of rules, you can set the current field validation rules, validation fails to enter the insert failed.

  • required: true will pass fields
  • minlength: 3 minimum string length
  • maxlength: 20 Maximum string length
  • min: 2 minimum value of 2
  • max: 100 to 100 maximum value
  • enum: [ 'html', 'css', 'javascript', 'node.js'] enumeration, include available items, if not given the enumeration will range
  • trim: true removing spaces to the string
  • validate: custom validator
  • default: default value

Get the error message: error.errors [ 'Field Name'] .message

Example :

// 创建集合规则
const PostSchema = new mongoose.Schema({
    title:{
        type:String,
        required:[true,'文章内容不能为空'],
        minlength:[2,'文章内容不能小于2个字'],
        maxlength:[10,'文章内容不能大于10个字'],
        //去除字符串两边的空格
        trim:true
    }
});
const Post = mongoose.model('Post',PostSchema);
Post.create({title:'123'}).then(result => console.log(result));

Description: Validation rules can pass a single item or an array, the second value is a custom error message

Custom validation rules, and to handle error messages

const PostSchema = new mongoose.Schema({
    title:{
        type:String,
        required:[true,'文章内容不能为空'],
        minlength:[2,'文章内容不能小于2个字'],
        maxlength:[10,'文章内容不能大于10个字'],
        //去除字符串两边的空格
        trim:true
    },
    author:{
        type:String,
        validate:{//自定义验证规则
            validator: v =>{
                //返回布尔值,true验证成功,false验证失败,v为需要验证的值
                return v && v.length > 4
            },
            //自定义错误
            message: '输入的值不匹配'
        }
    }
});
const Post = mongoose.model('Post',PostSchema);
Post.create({title:'123',author:''}).then(result => console.log(result))
.catch(error => {
    //获取信息错误对象
    const errors = error.errors;
    //循环错误对象
    for(attr in errors){
        //将错误信息打印
        console.log(errors[attr].message);
    }
});

3.8 set associative

Usually there is a relationship between different sets of data , such as article information and user information stored in different collections, but the article is published by a user, all of the information to be queried articles published include users, you need to use a set of associations.

  • Id associated with the use of collection

  • Use populate a set of methods associated queries

// 用户集合
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } })); 
// 文章集合
const Post = mongoose.model('Post', new mongoose.Schema({
    title: { type: String },
    // 使用ID将文章集合和作者集合进行关联
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}));
//联合查询
Post.find()
      .populate('author')
      .then((err, result) => console.log(result));

Guess you like

Origin www.cnblogs.com/royal6/p/12527415.html