Article Directory
Ready to work
We first need to ensure that you have started MongoDB, if not start 以管理员身份
running cmd
net start mongoDB
Secondly, you need to install third-party module
npm install mongoose
And introduced
const mongoose = require(‘mongoose’);
Related concepts Database
the term | Explanation |
---|---|
database | Database (data warehouse) |
collection | Collection, a collection of data, as can be appreciated in the array js |
document | Documents, a specific data, can be understood as the object's js |
field | Field, the document property name can be understood as js in the object properties |
In a database software can contain multiple data warehouse can contain multiple sets of data in each data warehouse, in each data set may also contain a number of documents (specific data), and each set of which they can It contains multiple fields
Specifically from the image below
- Data warehouse: admin, config, local (which is the software that comes with three), playground (create yourself)
- Set (in playground chestnut): posts, students, tests, users
- Document: the right side in FIG. 3 in the document
- Fields: _id (soft-create yourself, this data is unique identification ), name, age, email
Connect to the database
mongose.connect('mongodb://localhost/playground', {
useNewUrlParser: true
})
.then(() => console.log('数据库连接成功'))
.catch(err => {
console.log(err);
console.log('数据库连接失败');
});
When you are using a database, if the database does not exist, then MongoDB will automatically create the database. Also, if only to create a database without adding to the data inside the database, then you refresh MongoDB Compass
will not see this database, because there is no collection (that is, no data)
Create Collection
Create a collection can be divided into two steps:
the corresponding rule 1. collection set, this is the data that you created (document) which contains what (objects), these elements have any requirements
2. Create collections based on rules
//创建规则
let userSchema = new mongose.Schema({
name: String,
age: Number,
hobbies: [String]
});
//根据规则创建集合
//这里要写大写字母,但是在软件中你会看到小写并加了s
let User = mongose.model('User', userSchema); //users
Create documents (specific data)
There are two ways to create a document
// 创建文档的第一种方法
let data = {
name: '张三',
age: 19,
hobbies: ['跑步', '睡觉']
};
let person1 = new User(data);
//将数据保存到数据库中1
person1.save();
// 创建文档的第二种方法
//对返回结果的处理方式
User.create(data, (err, doc) => {
if(!err) {
console.log(doc);
} else {
console.log(err);
}
});
//我感觉还是这一种看着舒服(嘿嘿~~~~)
User.create(data)
.then(doc => {
console.log(doc);
})
.catch(err => {
console.log(err);
});
Query document (data)
//根据条件查找文档,如果条件为空则查询所有数据
//返回的是一个数组,数组里的每一项为一个对象
//查询名叫张三的
User.find({name: '张三'}).then(result => console.log(result));
//查找年龄大于20小于30的
User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result));
// 返回的是一个对象,默认返回当前集合中的第一条文档
User.findOne({name: '张三'}).then(result => console.log(result));
//对查找到的数据进行处理
// 查询所有数据中的指定字段
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));
// 查询的数据跳过前两条结果 限制显示5条结果,通常用于数据的分页显示
User.find().skip(2).limit(5).then(result => console.log(result));
Deleting a document (data)
// 查找到一条文档并且删除
// 返回删除的文档,如果查询到多条文档,那么将会删除第一条
User.findOneAndDelete({name: '张三'}).then(result => console.log(result));
// 删除多条文档,没有条件则删除调所有的数据
User.deleteMany({}).then(result => console.log(result));
Update Documentation
// 更新一条数据
// 第一个参数:要更那条数据
// 第二个参数:更新那些内容
User.updateOne({name: '李四'}, {name: '李狗蛋' ,age: 28, }).then(result => console.log(result));
// 更新多个数据
User.updateMany({}, {age: 66}).then(result => console.log(result));
La la la
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground')
.then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败'))
let bookSchema = mongoose.Schema({
name: {
type: String,
required: [true, '请输入书的名称'],
minlength: [2, '名称长度不能少于2个字'],
maxlength: [20, '文章长度不能大于20个字'],
trim: true
},
author: {
type: String,
validate: {
validator: value => {
// 返回布尔值
// true 验证成功
// false 验证失败
// value 要验证的值
return value && value.length > 4
},
//自定义错误信息
message: '不符合规定'
}
},
category: {
type: String,
enum: {
values: ['html', 'css', 'js'],
message: '没有该类别'
}
},
num: {
type: Number,
min: [0, '不能少于0本'],
max: [100, '不能多于100本']
},
publishDate: {
type: Date,
default: Date.now
}
});
let Book = mongoose.model('Book', bookSchema);
Book.create({name: ' JavaScript程序设计 ', author: 'he', category: 'jss', num: 8,})
.then(doc => console.log(doc))
.catch(error => {
// 获取错误信息对象
const err = error.errors;
// 循环错误信息对象
for (var attr in err) {
// 将错误信息打印到控制台中
console.log(err[attr]['message']);
}
})