MongoDB
1:如何连接Mongodb数据库
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('数据库连接成功'))
.catch(err => console.log(err, '数据库连接失败',));
2:集合规则+创建集合(new mongoose.Scheme({})+mongoose.model(‘name’,集合规则))
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
});
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: ['html', 'css', 'javascript', 'node.js'],
message: '分类名称要在一定的范围内才可以'
}
},
author: {
type: String,
validate: {
validator: v => {
return v && v.length > 4
},
message: '传入的值不符合验证规则'
}
}
});
3:插入文件+创建数据项(new 集合({})+ 集合.create({}))
const Course = mongoose.model('Course', courseSchema);
const course = new Course({
name: 'Node.js course',
author: 'wangjian',
isPublished: true
});
course.save();
const Course = mongoose.model('Course', courseSchema);
Course.create({ name: 'JavaScript基础', author: '黑马讲师', isPublish: true })
.then(doc => console.log(doc))
.catch(err => console.log(err));
Course.find({
name: 'wangjian',
isPublished: true
})
.limit(10)
.sort({ name: 1 })
.select({ name: 1, tags: 1 })
.exec((err, data) => { })
4:条件查询例子
const User = mongoose.model('User', userSchema);
5:删除文档
User.deleteMany({}).then(result => console.log(result))
6:更新文档
const User = mongoose.model('User', userSchema);
User.updateMany({}, { age: 300 }).then(result => console.log(result))
7:集合联合查询
Post.find().populate('author').then(result => console.log(result))
8:在catch中的错误信息
const Post = mongoose.model('Post', postSchema);
Post.create({ title: 'aa', age: 60, category: 'java', author: 'bd' })
.then(result => console.log(result))
.catch(error => {
const err = error.errors;
for (var attr in err) {
console.log(err[attr]['message']);
}
})
附:User测试:
{
"_id": {
"$oid": "5c09f1e5aeb04b22f8460965"
},
"name": "张三",
"age": 20,
"hobbies": [
"足球",
"篮球",
"橄榄球"
],
"email": "zhangsan@itcast.cn",
"password": "123456"
}
{
"_id": {
"$oid": "5c09f236aeb04b22f8460967"
},
"name": "李四",
"age": 10,
"hobbies": [
"足球",
"篮球"
],
"email": "lisi@itcast.cn",
"password": "654321"
}
{
"_id": {
"$oid": "5c09f267aeb04b22f8460968"
},
"name": "王五",
"age": 25,
"hobbies": [
"敲代码"
],
"email": "wangwu@itcast.cn",
"password": "123456"
}
{
"_id": {
"$oid": "5c09f294aeb04b22f8460969"
},
"name": "赵六",
"age": 50,
"hobbies": [
"足球",
"篮球",
"橄榄球"
],
"email": "zhaoliu@itcast.cn",
"password": "123456"
}
{
"_id": {
"$oid": "5c09f2b6aeb04b22f846096a"
},
"name": "大神",
"age": 32,
"hobbies": [
"足球"
],
"email": "dashen@itcast.cn",
"password": "123456"
}
{
"_id": {
"$oid": "5c09f2d9aeb04b22f846096b"
},
"name": "小白",
"age": 14,
"hobbies": [
"橄榄球"
],
"email": "xiaobai@163.com",
"password": "123456"
}