node js 链接 MongoDB数据库操作
2020年7月21日MongoDB 术语
1 2 3 4 |
database //数据库 相当于mysql 数据库 collection //集合 相当于mysql 表 document //文档 相当于mysql 一行数据 field //字段 相当于mysql 字段 |
连接操作MongoDB使用的包
1 |
npm install mongoose |
mongoose的基本使用
英文文档mongoose https://mongoosejs.com/docs/guide.html
导入数据
windows使用这个命令如果失败,前添加系统环境变量,我的是C:\Program Files\MongoDB\Server\4.2\bin
文件下
1 |
mongoimport -d 数据库名 -c 集合名称 --file 要导入的数据文件 |
连接数据库
1 2 3 4 5 6 7 8 |
const mongoose = require('mongoose') /** * 连接数据库的方法 */ mongoose.connect('mongodb://localhost:27017/zf', {useUnifiedTopology: true}) .then(success => console.log(success + '连接成功')) .catch(error => console.log(error + '连接失败')) |
创建数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
/** * 定义集合(表)中的字段和 * 一些验证规则 */ const userSchema = new mongoose.Schema({ name : String, age : Number, password: String, isAuth : Boolean }) /** * 创建模型,并且添加验证规则 */ const UserModel = mongoose.model('user', userSchema) /** * 创建文档方式一 * **************************** * 使用模型创建一条数据创建 * 的过程中验证数据是否正确 */ const userModel = new UserModel({ name:'张舫', age: 18, password:'123123', isAuth:true }) userModel.save() //可以把save()链式到上面 /** * 创建文档方式二 我可能最喜欢这种方式了 * **************************** * 使用模型创建一条数据创建 * 的过程中验证数据是否正确 */ UserModel.create({name: '张舫2', age: 81, password: '123123', isAuth: true}) .then(success => console.log(success)) .catch(error => console.log(error)) |
查询数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* *************************************************************** * 查找所欲数据数据 * $gt 代表大于 * $lt 代表小于 * $in 代表包含 和 mysql 的 in一致 * *************************************************************** * select() 选择需要的字段 id默认是选中的, 如果想取消选中前面加 -(减号)即可 * *************************************************************** * sort() 默认升序排序 .如果想降序排序前面加 -(减号)即可 * *************************************************************** * skip() 和mysql offset 一样 * *************************************************************** * limit() 和mysql limit 一样 * */ UserModel.find({password: {$gt: 10, $lt: 90} ,name: {$in: ['张舫']}}) .select('name age password -_id') .sort('-age') .skip(5) .limit(1) .then(success => console.log(success)) .catch(error => console.log(error)) |
删除数据
1 2 3 4 5 6 |
/** * 查找一条数据并删除 */ UserModel.findOneAndDelete({_id: '5f16f5ced36ad32580f284eb'}) .then(success => console.log(success)) .catch(error => console.log(error)) |
1 2 3 4 5 6 7 |
/** * 删除多条数据,注意如果传入{} 空集,就全部删除了 * 返回成功的值为 { n: 24, ok: 1, deletedCount: 24 } */ UserModel.deleteMany({name: {$in: ['张舫']}}) .then(success => console.log(success)) .catch(error => concole.log(error)) |
修改数据
1 2 3 4 5 |
/** * 查找多个数据并修改 , 注意查找时别传入{}空对象否则全部修改 * 返回值 :{ n: 6, nModified: 6, ok: 1 } */ UserModel.updateMany({age: {$in: 81}}, {age: 300}).then(result => console.log(result)) |
模型常用验证规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
/** * 验证规则 */ new mongoose.Schema({ title: { type : String, //必须是字符串类型 required : [true, '请传入文章标题'], //必填 minlength: [2, '文章长度不能小于2'], //文本长度不小于 maxlength: [5, '文章长度最大不能超过5'], //文本长度不大于 trim : true //去除文本左右两侧空格 }, age: { type: Number, //必须是数字类型 min : 18, //不小于18 max : 100 //不大于100 }, publishDate: { type : Date, //必须是时间类型 default: Date.now //定义默认值 }, category: { type : String, //必须是字符串类型 language: { values : ['js', 'python', 'php'],//枚举值 必须是values中存在的 message: '分类名称要在一定的范围内才可以' } }, author: { type : String, content: { validator: v => { //使用自定义验证方法 return v && v.length > 4 }, message : '传入的值不符合验证规则' } } }); |
集关联
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
const mongoose = require('mongoose') mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true,useUnifiedTopology: true}) .then(success => console.log(success+'连接成功')) .catch(error => console.log(error+'连接失败')) /** * 创建一个用户模型并且添加用户规则 */ userModel = mongoose.model('user', mongoose.Schema({ name: { type : String, required : [true, '请填写用户名'], minlength: [1, '请输入大于1位的用户名'], maxlength: [40, '请输入小于40位用户名'] }, age: { type : Number, required: [true, '请填写年龄'], min : [18 , '你必须要要大于18哦'], max : [150 ,'好像还没有人能活这么久吧'] }, sex: { type : String, required: [true, '请填写性别'], values : ['男', '女'], message : '不可以出现妖' } })) /** * 创建一个文章模型 */ articleModel = mongoose.model('article',mongoose.Schema({ title:{ type : String, required :[true,'文章标题必须填写'], minlength: [1, '请输入大于1位的标题'], maxlength: [40, '请输入小于40位标题'], }, content:{ type :String, required:[true,'文章内容为必填项'], }, author:{ type :mongoose.Schema.Types.ObjectId, ref :'user' }, })) /** * 查找文章所属作者(一对一) */ articleModel.findOne().populate('author').then(success=>{ console.log(success) }) /** * 作者查找文章 ,一对多 * 我不知道有没有更优雅的方法 * laravel 的一对多和 多对多 十分优雅 */ userModel.findOne().then(success => { articleModel.find({'author': success.id}).then(success => { console.log(success) }) }) /** * 数据填充方法 * 如果你想使用我的数据作为填充对象的话 * 你别忘记执行这个方法, fill() */ function fill() { for (let i = 0; i < 2; i++) { userModel.create({ name: `张舫${Math.random()}`, age : 18, sex : '男' }).then((success) => { for (let i = 0; i < 10; i++) { articleModel.create({ title : `文章标题${Math.random()}`, content: '文章内容啊啊啊啊', author : success._id, }) } }) } } |