Node Tutorial --MongoDB database

MongoDB database to explain

Why use a database?

Website on the Internet There are two major categories, static as well as dynamic and static Web site on Needless to say, the so-called dynamic website is that you can get different results according to the corresponding request, what this means, it can be felt you, you just need to know the current standard dynamic website is to get away

Why do we use MongoDB? mysql okay? Of course, no problem. but! Learning MongoDB learning costs are lower, what does that mean? I mean, because the MongoDB database development interface is a js syntax, as well as internal storage format is json all you particularly easy to use,

MongoDB is a software to download it juveniles

It should be two software is a database software itself, there is a visual database software
Baidu click download to get away! I think I have no need to teach you how to install the software,
one thing should be noted, you need to know about these two folders for later troubleshooting
how to view your MongoDB has been installed successfully? In fact, this software will open a port on your computer
localhost: 27017, there is no error if you visit, it means that you have successfully installed the software

Database Basics

  1. Data warehouse, database
    so-called data warehouse refers to a database software that provides services to multiple sites, each site has its own corresponding data warehouse, data warehouse is content on this site
  2. Collection, Collection
    collection is in a warehouse, a collection of data, can be understood as an array js
  3. Document, document
    set below the document, the document is a specific data, an object is similar to js
  4. Field, field
    documentation which has fields corresponding to the data, what is the field? Js equivalent to the key values of the key, of course, you also can be understood as an object of property

A bit fuzzy? It's ok. Look at this chart below, you will feel more cool

Using a database (a)

  1. First of all, we open our software. You do not need to make any changes, just click the link to get away.

  2. Second, we look at what's inside the database admin note here also there are local config Do not move! ! !
    Click Create to create a warehouse, we create a name called api warehouse

  1. And then we create a warehouse, the following is my database, and inside all things created here is very simple, because the software provides a visual, so the operation is very easy

  2. Then you probably depressed, wow there are so many field data, talk of the town, you leave me a play? You want to eat fart,
    it does not matter! You know you lazy ah, we can directly import the following way existing data, pay attention to, ah, here before you no longer use GUI software, and we change the software that took years of development in which there were, MongoBooster,
    instructions for use: you just Baidu about it, very simple to use it! Json file can be dragged back to complete the import of a database

Use Database (two)

You thought it would get away with a GUI? ? No no no no, you are a programmer, brother! You need to use the code! ! !

  1. In Node download a dependent npm install mongoose, so you can manipulate the database by Node
  2. In MongoDB start the computer, use the two commands. Start the service: net start mongoDB close the service: net stop mongoDB
  3. Link to your own database node in the
    syntax:
// 注意我们的返回的是一个promise对象
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
//这个是返回一个promise对象,(异步,
//这个地方没有playground也是ok的,如果没有他会自己帮我创建这个数据库
// { useNewUrlParser: true }这个参数不用管你加上就完事
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));

Use database (III increase)

Guidance: If our library does not automatically create a library,

With the library, we can create the next level of the library: a collection of

  • The first way to create
  1. Step 1: Set a set of rules
const mongoose = require('mongoose');
//对集合设定规则
  // 设定集合规则
 const courseSchema = new mongoose.Schema({
     name: String,
     author: String,
     isPublished: Boolean
 });
  // 创建集合并应用规则
  1. Step 2: Create a collection to get a collection on behalf of the constructor of the current collection, this collection is very important constructor
 const Course = mongoose.model('Course', courseSchema); // Course就是集合的名字。注意这里你需要给一个大写,
 //返回一个构造函数,然后我们拿东西去接过来就完事

  1. The third step is to throw something inside the database

//5.注意你需要插进数据,要不然它不会创建出来

// 6.把集合实例创建出来,并且把数据传入,于是乎你就有了一个数据对象,也就是创建文档
let coures = new Course({
    name: 'node教程',
    author: '老李',
    isPublished: true
})


// 7.调用集合对象下的方法 插入数据
coures.save()
  • We still have a way to

// 第一个是数据库。第二个回调函数
//Course是之前的的构造函数
   Course.create({name: 'JavaScript基础', author: '老李', isPublish: true}, (err, doc) => { 
    //  错误对象
   console.log(err)
    //  当前插入的文档
   console.log(doc)
});

//有回调函数的时候基本上都是异步的api,Course.create()返回promise对象
Course.create({name: 'Node基础', author: '老李', isPublish: true})
     .then(doc => console.log(doc))
     .catch(err => console.log(err))

  • Import existing data through code

The syntax is based - on the command line. This is not a command Code:

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

Caution: In general, if it is to add some command window systems you need to look like to set the same

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

mongoimport -d playground -c users -file .\user.json

Use Database (IV deleted)

Note that the operation of all of our data api are under Coures collection constructor, I mean: Before we say that the set constructors, very important!

删除文档的语法:注意,他们都是返回promise对象,then之后都是拿到的被删除的文档,{}里卖是丢查询条件
 // 删除单个
Course.findOneAndDelete({}).then(result => console.log(result))
 // 删除多个 返回,一个对象ok:1表示操作成功。n:表示删除四个
User.deleteMany({}).then(result => console.log(result))


Use Database (Five, change)

Note that the operation of all of our data api are under Coures collection constructor, I mean: Before we say that the set constructors, very important!

In fact, ah change operation is an update operation

Basic syntax:

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

Combat demo:

// 找到要删除的文档并且删除
// 返回是否删除成功的对象
// 如果匹配了多条文档, 只会删除匹配成功的第一条文档
// User.updateOne({name: '李四'}, {age: 120, name: '李狗蛋'}).then(result => console.log(result))
// 找到要删除的文档并且删除
// 如果传递的是一个{} 表示修改所有的
User.updateMany({}, { age: 300 }).then(result => console.log(result))

Use Database (six check)

Note that the operation of all of our data api are under Coures collection constructor, I mean: Before we say that the set constructors, very important!
It's here

const Course = mongoose.model('Course', courseSchema); // Course就是集合的名字。注意这里你需要给一个大写,
 //返回一个构造函数,然后我们拿东西去接过来就完事

Look at how we do query
syntax:

//  根据条件查找文档(条件为空则查找所有文档)
 当前的集合构造函数.find().then(result => console.log(result))
注意它的返回值:数组,如果查询的数据不存在就会返回一个空数组

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

// 创建集合规则
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
    email: String,
    password: String,
    hobbies: [String] //这个是一个数组,数组里面是字符串
});

// 使用规则创建集合
const User = mongoose.model('User', userSchema); //返回是一个集合的构造函数

// 查询文档
// 查询用户集合中的所有文档
// User.find().then(result => console.log(result)); //find方法。返回的总是一个文档的集合(数组,需要说明的是,.then是promise对象的方法,这个返回的是程序的结果
// 通过_id字段查找文档
// User.find({ _id: '5c09f267aeb04b22f8460968' }).then(result => console.log(result))

// findOne方法返回一条文档 默认返回当前集合中的第一条文档
// User.findOne({ name: '李四' }).then(result => console.log(result))
// 查询用户集合中年龄字段大于20并且小于40的文档
// User.find({ age: { $gt: 20, $lt: 40 } }).then(result => console.log(result)) //这里有一些转意字符,你需要了解$gt = >号,$lt = <号
// 查询用户集合中hobbies字段值包含足球的文档,可以用于实现网站的搜索功能
// User.find({hobbies: {$in: ['足球']}}).then(result => console.log(result)) //$in是包含的意思
// 选择要查询的字段
// User.find().select('name email -_id').then(result => console.log(result))
// 根据年龄字段进行升序排列,可以用来实现价格的查询等等操作
// User.find().sort('age').then(result => console.log(result))
// 根据年龄字段进行降序排列
// User.find().sort('-age').then(result => console.log(result))
// 查询文档跳过前两条结果 限制显示3条结果,这个可以实现分页功能
User.find().skip(2).limit(3).then(result => console.log(result))
User.find().skip(2).limit(3).then(result => console.log(result))
skip(2)跳过前两个文档
limit(3)只想要三个
+++

总结:
// 返回的都是文档
find()是返回这个东西
[{
    _id: 5c0917ed37ec9b03c07cf95f,
    name: 'node.js基础',
    author: 'laoli'
},{
     _id: 5c09dea28acfb814980ff827,
     name: 'Javascript',
     author: 'laoli'
}]

findOne()返回是这个东西
{
    _id: 5c0917ed37ec9b03c07cf95f,
    name: 'node.js基础',
    author: 'laoli'
}

verification

The above does it mean? Refers to the setting of a field insertion rules, verify it and see your field character does not meet my rules, if they meet allows the user to insert field

Requirements: For example, here we create a collection of articles


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

//这里是做一些mongodb的验证,注意啊这里的规则可以是对象类型
const postSchema = new mongoose.Schema({
    title: {
        type: String,
        // 必选字段
        required: [true, '请传入文章标题'],
        // 字符串的最小长度
        minlength: [2, '文章长度不能小于2'],
        // 字符串的最大长度
        maxlength: [5, '文章长度最大不能超过5'],
        // 去除字符串两边的空格
        trim: true
    },
    age: {
        type: Number,
        // 数字的最小范围
        min: 18,
        // 数字的最大范围
        max: 100
    },
    publishDate: {
        type: Date,
        // 默认值
        default: Date.now //这个是会传出一个日期,这个是默认的传入的
    },
    category: {
        type: String,
        // 枚举 列举出当前字段可以拥有的值,这个是枚举,
        // 所谓的枚举 就是一个一个举例验证出来
        enum: {
            values: ['html', 'css', 'javascript', 'node.js'],
            message: '分类名称要在一定的范围内才可以'
        }
    },
    author: {
        type: String,
        //我们程序员自定义的验证规则
        validate: {
            validator: v => { //v是形参,是当前用户插入的值
                // 返回布尔值
                // true 验证成功
                // false 验证失败
                // v 要验证的值
                //短路运算
                return v && v.length > 4
            },
            // 自定义错误信息
            message: '传入的值不符合验证规则,最少是4个以上1'
        }
    }
});

const Post = mongoose.model('Post', postSchema);

//需求:如何一次性的把所有的不符合验证规则的错误信息都获取出来

Post.create({ title: 'aa', age: 60, category: 'java', author: 'bd' })
    .then(result => console.log(result))
    .catch(error => {
        // 获取错误信息对象,这个获取过来的其实就是报错的信息
        const err = error.errors;
        // 循环错误信息对象
        for (var attr in err) { //注意一下这个地方的for遍历循环的操作要点
            // 将错误信息打印到控制台中
            console.log(err[attr]['message']);
        }
    })

MongoDB Advanced - associated collection

This is more difficult
requirements: in a data includes other data.

There is a relationship between different sets of data generally, for example, 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 the collection
collection methods associated queries using populate

Syntax Specification:

// 用户集合
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } })); 
// 文章集合
const Post = mongoose.model('Post', new mongoose.Schema({
    title: { type: String },
    // 使用ID将文章集合和作者集合进行关联,是一个id的类型mongoose.Schema.Types.ObjectId,固定死的,第二个参数就是关联谁
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}));
//联合查询
Post.find()
      .populate('author')
      .then((err, result) => console.log(result));

Sample code:

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

// 用户集合规则
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    }
});
// 文章集合规则
const postSchema = new mongoose.Schema({
    title: {
        type: String
    },
    author: {
        type: mongoose.Schema.Types.ObjectId, //注意一下 mongodb的id是有一种特殊类型的,这个就是那个类型
        ref: 'User' //ref就是关联的意思!指定关联另外一个集合
    }
});
// 用户集合 
const User = mongoose.model('User', userSchema);
// 文章集合
const Post = mongoose.model('Post', postSchema);

// 创建用户
User.create({ name: 'itheima' }).then(result => console.log(result));
// 创建文章
Post.create({ titile: '123', author: '5c0caae2c4e4081c28439791' }).then(result => console.log(result));
//查询作者
Post.find().populate('author').then(result => console.log(result))

Guess you like

Origin www.cnblogs.com/BM-laoli/p/12661594.html