mongoDB

一、mongoDB + Node.js 的增删改查

  mongoDB下载地址 : https://www.mongodb.com/try/download/community

  1、node.js依赖于第三方包 :mongoose操作mongoDB, 所以需要先下载 :npm install mongoose

  2、需要先引入mongoose 第三方包 : const mongoose = require( ' mongoose ' ) ;

  3、连接数据库:  

    注:node的所有操作数据库的方法,都返回Promise对象,如果连接的数据库不存在,会在添加完数据后自动创建   

1   mongoose.connect('mongodb://localhost/ 数据库名 ' ,
{ useNewUrlParser : true, useUnifiedTopology: true }) 2   .then(()=> console.log(' 数据库连接成功 ')) 3 .catch(()=> console.log(' 数据库连接失败 '))

  4、创建集合规则(集合相当于数据表), Schema是一个构造函数,在它的实例对象里面填写规则

  例如创建一个用户表的规则:

    const userSchema = new mongoose.Schema({
         name : String,
        age : Number,
        email : String,
        password : String,
        hobbies : [String]
       // hobbies 里面存的是一个数组
    })    

  5、创建集合,参数1是集合名(相当于表名),首字母必须大写,但是在数据库中显示为  users,参数2是规则, 返回的是一个构造函数 

1     const User = mongoose.model(' User ', userSchema);

  6、向集合中添加文档(文档就是数据),用集合返回的构造函数的实例对象添加, 默认会添加id 为 _id

1 const user = new User({
2     name: '丫丫' ,
3     age : 37 ,
4     hobbise : ['唱歌','跳舞','好看'],
5     email : "tongliya@love.com" ,
6     password: "yayaya"
7 })

  7、添加的另一种写法

1 User.create({
2      name: '丫丫' ,
3      age : 37 ,
4      hobbise : ['唱歌','跳舞','好看'],
5      email : "tongliya@love.com" ,
6      password: "yayaya"
7 })
8 .then(result=>console.log(result))
9 .catch(err=>console.log(err))

  8、查询

  (1)、查询用户集合中的所有文档,返回的是查询到的数据

1    User.find().then(result=>console.log(result))

  (2)、根据条件查询数据

1   User.find({age: '20'}).then(result=>console.log(result))

  (3)、条件查询,只查询一条数据

1    User.findOne({age: '20'}).then(result=>console.log(result))

  (4)、查询年龄大于20,小于50的数据

1    User.find({age: {$gt: '20', $lt: '50'}}).then(result=>console.log(result))

  (5)、查询爱好为打豆豆的数据,注:爱好是一个数组

1    User.find({hobbise: {$in: [' 打豆豆 ']}}).then(result=>console.log(result))

  (6)、查询某些指定字段, 查询哪些字段就写进select中,用空格隔开,不想查询哪些字段,就在前面加  -, 如 -_id,默认会查询 _id

1    User.find().select(' name email -_id ').then(result=>console.log(result))

  (7)、对查询字段进行升序,用sort(),降序只要在字段前加上 -

1    User.find().sort(' age ').then(result=>console.log(result))        // 对查询到的字段按年龄进行升序排列
2 
3    User.find().sort(' -age ').then(result=>console.log(result))    // 对查询到的字段按年龄进行降序排列

  (8)、查询年龄是10,20,25的选项

1     User.find({age: {$in: [10, 20, 25]}}).then(result=>console.log(result))

  (9)、skip 跳过多少条数据, limit 限制查询多少条数据

1    User.find().skip(2).limit(2).then(result=>console.log(then))
   // 查询到的数据跳过前两条,剩下的结果中只查询头两条

  9、删除

  (1)、查找到一条文档并且删除,返回删除的文档,如果查询匹配到多个文档,那么将删除第一条文档

1  User.findOneAndDelete({_id: '5c09f2d9aeb04b22f846096b'}).then(result=>console.log(result));

  (2)、删除多条文档,返回值是一个对象 { n: (删除多少条文档), ok: 1, deletedCount: (删除的总数) }

1   User.deleteMany({_id: '5c09f267aeb04b22f8460968'}).then(result=>console.log(result));

   10、更新

  (1)、更新集合中的文档(更新一个), 第一个参数是查询条件, 第二个参数是修改的值, 返回: { n: 1, nModified: 1, ok: 1 }

1    User.updateOne({name: '李四'}, {age: '30'}).then(result=>console.log(result));

  (2)、更新集合中的文档(更新多个), 第一个参数不写表示选择全部

1    User.updateMany({}, {age: '50'}).then(result=>console.log(result));

  二、mongoose验证

  1、在创建集合规则时,可以设置当前字段的验证规则,验证失败就数据插入失败

  

   如:当前创建一个post集合: 

 1 const postSchema = new mongoose.Schema({
 2     title: {
 3         //设置标题类型为字符串
 4         type: String,
 5         //设置选项为必填, 相当于 not null , 也可 required: true, 不设置错误提示,
 6         required: [true, '标题不能为空'],
 7         //设置最小长度
 8         minlength: [2, '标题最小长度为2'],
 9         //设置最大长度
10         maxlength: [10, '标题最大长度为10'],
11         //去除字符创两边的空格
12         trim: true
13     },
14     age: {
15         type: Number,
16         min: [2, '年龄不得低于2'],
17         max: [100, '年龄不得大于100']
18     },
19     publishDate: {
20         type: Date,
21         //设置默认值为当前时间
22         default: Date.now
23     },
24     category: {
25         type: String,
26         // 枚举,列举出当前字段可以存入的值,如果存入的不在这些值中,报错
27         // enum: ['html', 'js', 'java', 'php'],
28         enum: {
29             values: ['html', 'js', 'java', 'php'],
30             message: '分类名称不正确'
31         }
32     },
33     author: {
34         type: String,
35         //自定义验证信息
36         validate: {
37             //验证器: v代表传入的值
38             // 返回值是boolean, true表成功, false表失败
39             validator: (v)=>{
40                 return v && v.length > 4
41             },
42             // 自定义错误信息
43             message: '传入的参数不符合验证规则'
44         }
45     }
46 });

  2、定义错误提示

  插入数据时返回的promise对象我们可以用then去捕获成功时返回的数据,也可以用catch去捕获失败时的数据

1 Post.create({title: 'aa', age: 20, category: 'hmtl', author: '丫丫丫丫'})
2 .then(result=>console.log(result))
3 .catch(error=>console.log(error));

   返回一个error对象,里面有个errors属性,包含了错误返回的字段对象,我们可以精简一下返回的错误信息

1 Post.create({title: 'aa', age: 20, category: 'hml', author: '丫丫丫'})
2 .then(result=>console.log(result))
3 .catch(error=>{
4     const err = error.errors;
5     for(let attr in err){
6         console.log(attr,err[attr].message)
7     }
8 });

   

  三、集合关联

  通常不同集合的数据之间是有关联的,如用户信息和文章信息之间,需要知道某篇文章是哪个用户发表的,此时就需要在文章信息里面关联用户的主键,此时需要集合关联,(相当于外键)

  

  接下来我们试着去关联用户信息和文章信息

  1、先创建用户集合和文章集合

 1 const User = mongoose.model('User', new mongoose.Schema({
 2     name: {
 3         type: String,
 4         required: [true, '请输入用户名'],
 5         minlength: [2, '用户名最小长度为2字符'],
 6         maxlength: [8, '用户名最大长度为8字符']
 7     }
 8 }))
 9 
10 const Post = mongoose.model('Post', new mongoose.Schema({
11     title: {
12         type: String,
13         required: [true, '请填写标题'],
14         minlength: [2, '标题最小长度为2字符'],
15         maxlength: [15, '标题最大长度为15字符']
16     },
17     // author里需要关联发表的作者的ID
18     author: {
19         // mongodb里面的id类型如下:
20         type: mongoose.Schema.Types.ObjectId,
21         // 关联那个集合
22         ref: 'User'
23     }
24 }))

  2、创建一个用户

1 User.create({name: '丫丫'})
2   .then(result=>console.log(result))

  3、创建一篇文章

  注:先去mongodb里面拿到作者的id, 写入author里

1 Post.create({title: '丫丫的小粉丝', author: '5f1be33c53621008b850930d'})
2   .then(result=>console.log(result))

  4、此时我们去查询文章信息

1 Post.findOneAndDelete({_id: '5f1be5e93ba53f3df886b068'})
2   .then(res=>consolr.log(res))

此时查询到的用户信息是用户的id,那如果我们想要查询文章信息的同时又得到用户信息该怎么做呢??

  5、联合查询

  在find()后面打点一个 populate方法,里面的参数是有进行关联的文档

1 Post.find({title: '丫丫的小粉丝'}).populate('author')
2   .then(result=>console.log(result))

原文地址:https://www.cnblogs.com/hxblogs/p/13375357.html