MongoDB 数据库概述及环境搭建参见:
https://www.cnblogs.com/joe235/p/12803421.html
下面把命令汇总下,方便查找:
1、创建一条数据
因为数据总得有个归类,所以需要提前设置好这个类的格式、名称
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true}) .then(() => console.log('数据库连接成功')) .catch(err => console.log(err, '数据库连接失败')); // 构造函数实例化 设置格式,字符串、数字、布尔值 const courseSchema = new mongoose.Schema({ name: String, author: String, isPublished: Boolean }); // 用上边的规定,创建类 // 名称首字母要大写,实际上数据库中生成的名字是courses const Course = mongoose.model('Course', courseSchema) // courses // 创建一条数据 const course = new Course({ name: 'node.js基础', author: '黑马讲师', isPublished: true }); // 保存到数据库 course.save();
2、创建一条数据第二种方法
create方法就是向集合中插入文档
// 写法一:回调函数 Course.create({name: 'Javascript', author: '黑马讲师', isPublished: false}, (err, result) => { console.log(err) console.log(result) }) // 写法二:promise对象 Course.create({name: 'Javascript123', author: '黑马讲师', isPublished: false}) .then(result => { console.log(result) })
3、将现成的数据导入到数据库中
命令行语法:
mongoimport -d 库名称 -c 类名称 --file 要导入的json数据文件
例如:
mongoimport -d playground -c users --file ./user.json
4、查询数据 删除数据 修改数据
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)); // 通过_id字段查找文档,返回的是数组 User.find({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result)) // 返回一条数据,默认返回集合中的第一条文档 User.findOne({name: '李四'}).then(result => console.log(result)) // 查询用户集合中年龄字段大于20并且小于40的文档 User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result)) // 查询用户集合中hobbies字段值包含足球的文档 User.find({hobbies: {$in: ['足球']}}).then(result => console.log(result)) // 把所有数据只显示name email,不显示id 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.findOneAndDelete({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result)) // 删除多条文档,大括号内写查询条件,不写就全部删除 User.deleteMany({}).then(result => console.log(result)) // 更改一条,第一个大括号是筛选条件,第二个是新内容 User.updateOne({name: '李四'}, {age: 18, name: '李狗蛋'}).then(result => console.log(result)) // 更改多条,第一个大括号是筛选条件,第二个是新内容 User.updateMany({}, {age: 18}).then(result => console.log(result))
5、验证规则
设定限制条件,决定让不让数据上传
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true }) .then(() => console.log('数据库连接成功')) .catch(err => console.log(err, '数据库连接失败')); 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: ['游戏区', '生活区', '搞笑区', '音乐区'], message: '没有此分类' } }, // 自定义验证条件 author: { type: String, // 要求返回布尔值,直接代表上传成功与失败 validate: { validator: v => { return v && v.length > 4 }, // 自定义错误信息 message: '传入的值不符合验证规则' } } }); const Post = mongoose.model('Post', postSchema); Post.create({ title: 'aa', age: 60, category: '舞蹈区', author: 'bd' }) // 上传成功的返回结果 .then(result => console.log(result)) // 上传失败的返回结果 .catch(error => { // 获取错误信息对象 const err = error.errors; // 循环错误信息对象,把前面几种错误写一起 for (var attr in err) { // 将错误信息打印到控制台中 console.log(err[attr]['message']); } })
7、数据关联
两个类:文章、作者;要做到显示文章数据时也显示作者数据。
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写到里面进行关联 author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }); // 用户集合 const User = mongoose.model('User', userSchema); // 文章集合 const Post = mongoose.model('Post', postSchema); // 先创建用户,得到id:5c0caae2c4e4081c28439791,完事后注释掉 // User.create({name: 'itheima'}).then(result => console.log(result)); // 再创建文章,注入用户id // Post.create({titile: '123', author: '5c0caae2c4e4081c28439791'}).then(result => console.log(result)); // 最后进行查询用populate()方法 Post.find().populate('author').then(result => console.log(result))