mongose操作数据库 增删改

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
92
93
94
95
96
97
98
99
100
101
102
103
//引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
//数据库连接
mongoose
.connect('mongodb://localhost/playground', { useNewUrlParser: true })
.then(res => {
//连接成功
console.log('数据库连接成功');
})
.catch(err => {
console.log('数据库连接失败');
});
 
//创建集合规则
const userSchame = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String],
});
//使用规则创建集合 1.集合名称 2.集合规则
const User = mongoose.model('User', userSchame); //courses
 
// //创建构造函数的实例
// const course = new User({
// name: '大四1',
// age: 41,
// email: '44444',
// password: 44444,
// hobbies: ['听音乐'],
// });
// //将文档插入到数据控中
// course.save();
 
//查询用户集合中的所有文档
// User.find().then(res => console.log(res));
// 62aaab3d0d67056a0659857f
//通过_id字段查找文档 find返回一组 findOne返回一个
// User.find({ _id: '62aaab3d0d67056a0659857f' }).then(res => console.log(res));
 
//findOne方法返回一条文档 默认返回当前集合中的第一条文档
// User.findOne({ _id: '62aaab3d0d67056a0659857f' }).then(result =>
// console.log(result)
// );
//$gt大于 $lt小于 查询用户集合中年龄字段大于20并且小于40的文档
// User.find({ age: { $gt: 20, $lt: 40 } }).then(res => {
// console.log(res);
// });
//匹配包含
// User.find({ hobbies: { $in: ['1'] } }).then(result => {
// console.log(result);
// });
//查询用户的名字和邮箱字段》
//选择要查询的字段
// User.find()
// .select('name email')
// .then(result => {
// console.log(result);
// });
//将数据按照年龄进行升序排序
// User.find()
// .sort('age')
// .then(result => {
// console.log(result);
// });
//将数据按照年龄进行降序排序
// User.find()
// .sort('-age')
// .then(result => {
// console.log(result);
// });
//skip跳过多少条数据 limit限制查询数量
// User.find()
// .skip(2)
// .limit(3)
// .then(res => {
// console.log(res);
// });
//删除单个
//查找到一条文档并且删除 返回删除的文档。如果匹配多个 会删除第一个
// User.findOneAndDelete({ _id: '62aac8c000556e5074ba73e5' }).then(res => {
// console.log(res, 'res');
// });
//删除多个 空{}会全部删除。。 返回对象 如 {n:4,ok:1} 4个被删,1为代表成功
// User.deleteMany({}).then(result => {
// console.log(result);
// });
 
//更新文档
//更新单个 第一个匹配到的
// User.updateOne({ 查询条件 }, { 要修改的值 }).then(result =>
// console.log(result)
// );//
// User.updateOne({ name: '李四' }, { name: '李狗蛋' }).then(result =>
// console.log(result)
// );
//更新多个
// User.updateMany({}, { password: '123456' }).then(result => console.log(result));
 
//mongoose验证
// 在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。
//required:true 必传字段

  

posted @   琴师i  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示