npm install mongoose 引入包
    1. //引入mongoose
    2. const mongoose = require('mongoose');
    3. //如果数据库里面没有它会自动创建;
    4. //连接mongooseDB数据库(如果执行了then函数就是连接成功了) // catch就是连接失败
    5. mongoose.connect('mongodb://localhost/数据库名').then(function(){
    6. console.log(''连接成功'');
    7. }).catch(function(){
    8. console.log(''连接成功'');)
    9. //创建(字段集合规则)表(规定字段类型)
    10. const stuSchema =new mongoose.Schema({
    11. name:String,
    12. age:Number
    13. })
    14. //创建一个表
    15. //把创建好的放到数据库里面去(表名在数据库中创建时会自动加s)
    16. //创建一个表时会返回表的对象
    17. //Students大写构造函数
    18. const Students = mongoose.model('student表名',stuSchema)
    19. //填充表的数据
    20. const stu = new Students({name:'小明',age:'20'})
    21. //保存
    22. stu.save();
    23. //创建新数据
    24. 第一种方式:
    25. Students.create({name:'西欧',age:18}要添加的数据,function(err失败,data成功返回数据到data){})
    26. 第二种方式:
    27. const promise = Students.create({name:'西欧',age:18})
    28. promise.then(data=>console.log(data)).catch(err=>console.log(err))
    29. //查询:
    30. //查询数据库里面的所有的数据(返回的一定是一个数组)
    31. Students.find().then(data=>{})
    32. //查询一条数据(返回的是一个对象,默认返回第一条数据)
    33. Students.findOne({条件name:'小明'}).then(data=>{})
    34. //删除:(要有正确的条件)
    35. //删除数据库中所有的数据
    36. Students.deleteMany({条件name:/^小/}).then(data=>{})
    37. Students.remove().then(data=>{})
    38. //删除数据库中第一条数据,且返回一个结果信息
    39. Students.deleteOne({条件name:/^小/}).then(data=>{})
    40. //findOneAndDelete() 表示查询符合条件的第一条数据并且把它删除,然后返回它删除之前的数据
    41. Students.findOneAndDelete({条件name:/^小/}).then(data=>{console.log(data)})
    42. //修改:
    43. //修改数据库中所有的数据
    44. Students.updateMany({条件name:/^小/},{修改成age:18}).then(data=>{})
    45. //修改数据库中第一条数据
    46. Students.updateOne({条件name:/^小/},{修改成name:'小雪',age:100}).then(data=>{})
    47. //findOneAndDelete() 表示查询符合条件的第一条数据并且把它修改,然后返回它之前数据
    48. Students.findOneAndUpdate({条件name:'小雪'},{修改成name:'小小'}).then(data=>{console.log(data)})
    49. //查询范围($gt大于)($lt小于)(大于10 小于30)
    50. const promise = Students.find({
    51. age: {
    52. $gt: 10,
    53. $lt: 30
    54. }
    55. })
    56. .then((data) => {
    57. console.log(data.length);
    58. })
    59. .catch((err) => {
    60. console.log(err);
    61. });
    62. //查询兴趣里面有喜欢吃的(包含$in)
    63. const promise = Students.find({
    64. hobbies: {
    65. $in: ['吃', '拉']
    66. }
    67. })
    68. .then((data) => {
    69. console.log(data.length);
    70. })
    71. .catch((err) => {
    72. console.log(err);
    73. });
    74. //查询名字中包含('婷'或者'娟'的人)
    75. const promise = Students.find({ name: /o|w/ })
    76. .then((data) => {
    77. console.log(data.length);
    78. })
    79. .catch((err) => {
    80. console.log(err);
    81. });
    82. //分页查询(每一页展示3条数据,查询第二页的数据)
    83. //skip()跳过多少条记录 limit()查询多少条 (跳过前面三条,查询第二页的三条)
    84. const page = 1; //页数
    85. const size = 3; //条数
    86. const promise = Students.find()
    87. .skip((page - 1) * size)
    88. .limit(size)
    89. .then((data) => {
    90. console.log(data.length);
    91. })
    92. .catch((err) => {
    93. console.log(err);
    94. });
    95. //排序查询(sort()年龄排序)
    96. const promise = Students.find()
    97. .sort('age')
    98. .then((data) => {
    99. console.log(data);
    100. })
    101. .catch((err) => {
    102. console.log(err);
    103. });
    104. //查询指定字段(select('age name')过滤)中间用空格隔开 , 不用的 -name
    105. const promise = Students.find()
    106. .select('name age -name')
    107. .then((data) => {
    108. console.log(data);
    109. })
    110. .catch((err) => {
    111. console.log(err);
    112. });
    1. //关联查询
    2. //ref()引用
    3. //populate(两表之间关联的字段)
    4. **//创建学生表字段
    5. const studSchema = new mongoose.Schema({
    6. name: {
    7. type: 'String'
    8. },
    9. t_id: {
    10. type: mongoose.Schema.Types.ObjectId, //学生表id类型写法
    11. ref: 'teacher' //ref()引用
    12. }
    13. });
    14. //创建创建一个学生表时表的对象
    15. const Studs = mongoose.model('Stud', studSchema);
    16. //填充表数据
    17. Studs.create({ name: '小婷', t_id: '626113cef519edb1f2f7e02b' });
    18. **//创建老师表字段类型
    19. const teacherSchema = new mongoose.Schema({
    20. name: String
    21. });
    22. //创建创建一个老师表时表的对象
    23. const Teachers = mongoose.model('teacher', teacherSchema);
    24. //填充表数据
    25. Teachers.create({ name: '老婷' });
    26. //关联查询 (查询学生属于哪个老师)
    27. const promise = Studs.find()
    28. .populate('t_id') //populate(两表之间关联的字段)
    29. .then((data) => {
    30. console.log(data);
    31. });
    1. //规定name必填:
    2. //required设置它为必填项 maxlength/minlength长度
    3. //trim: true 自动去首尾空格
    4. //规定年龄:
    5. //max/min 大小
    6. //规定性别:
    7. //enum 设置可迭代 values内容 message提示
    8. //createTime 创建时间 default设置默认值
    9. //自定义规则:
    10. //validate:{ 验证器validator(){}} 验证
    11. const userSchema = new mongoose.Schema({
    12. name: {
    13. type: String,
    14. required: [true, '姓名是必填项...'],
    15. maxlength: [4, '姓名长度最大为四...'],
    16. minlength: [2, '姓名长度最大为2...'],
    17. trim: true
    18. },
    19. age: {
    20. type: Number,
    21. max: [200, '年龄大了'],
    22. min: [0, '年龄小了']
    23. },
    24. sex: {
    25. type: Number,
    26. enum: {
    27. values: [0, 1],
    28. message: '性别只能是1或者0..'
    29. }
    30. },
    31. createTime: {
    32. type: Date,
    33. default: new Date()
    34. },
    35. //自定义规则
    36. email: {
    37. type: String,
    38. validate: {
    39. validator(val) {
    40. //正则验证/^\d{5,}@qq\.com$/.test(val)
    41. return /^\d{5,}@qq\.com$/.test(val); //如果返回true就是符合规则,不符合就不通过
    42. },
    43. message: '请输入正确的邮箱规则...'
    44. }
    45. }
    46. });
    47. const Users = mongoose.model('user', userSchema);
    48. //把email的值传给val
    49. Users.create({ name: 'oooo ', age: 15, sex: 1, email: '12345@qq.com' });