前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MongoDB数据库基本操作

MongoDB数据库基本操作

作者头像
用户3461357
发布2019-08-20 13:57:31
4.2K0
发布2019-08-20 13:57:31
举报
文章被收录于专栏:web前端基地web前端基地
  1. 安装

mongodb MongoDBcompass

  1. 配置mongoose

npm install mongoose

  1. node 连接数据库
代码语言:javascript
复制
const mongoose = require('mongoose');<br/>
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })<br/>
    .then( () => console.log('数据库连接成功'))<br/>
    .catch( err => console.log(err, '数据连接失败'))<br/>
  1. 通过创建集合实例创建文档
代码语言:javascript
复制
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
});

//使用创建集合  创建构造函数
const Course = mongoose.model('Course', courseSchema) //courses

//创建文档
const course = new Course({
    name: 'node.js基础',
    author: '一客',
    isPublished: true
});

//将文档插入数据库中
course.save();
  1. 通过集合构造函数方法(create)创建文档
代码语言:javascript
复制
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
});

//使用创建集合  创建构造函数
const Course = mongoose.model('Course', courseSchema) //courses

//创建文档
Course.create({name: 'Java', author: '贾淼', isPublished: false}, (err, result) => {
    console.log(err);
    console.log(result);
})
  1. 导入数据库操作
  • 配置命令行工具mongoimport

环境变量中配置mongoimport路径

  • 命令行执行

mongoimport -d playground(数据库名称) -c users(集合名称) --file ./user.json(导入文件)

  1. 查询文档
代码语言:javascript
复制
// 引入mongoose第三方模块 用来操作数据库
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))

// findOne方法返回一条文档 默认返回当前集合中的第一条文档
// 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))
// 选择要查询的字段
// 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))
  1. 删除文档

findOneAndDelete 单个 如果更新条件匹配多个默认只更新第一个 deleteMany 多个 第一个条件为空 默认更新所有(慎用)

代码语言:javascript
复制
// 引入mongoose第三方模块 用来操作数据库
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.findOneAndDelete({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
// 删除多条文档
User.deleteMany({}).then(result => console.log(result))
  1. 更新修改文档

updateOne 单个 如果更新条件匹配多个默认只更新第一个 updateMany 多个 第一个条件为空 默认更新所有

代码语言:javascript
复制
// 引入mongoose第三方模块 用来操作数据库
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.updateOne({name: '李四'}, {age: 120, name: '李狗蛋'}).then(result => console.log(result))
// 找到要删除的文档并且删除
User.updateMany({}, {age: 300}).then(result => console.log(result))
  1. mongoose验证
代码语言:javascript
复制
// 引入mongoose第三方模块 用来操作数据库
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: ['html', 'css', 'javascript', 'node.js'],
			message: '分类名称要在一定的范围内才可以'
		}
	},
	author: {
type: String,
		validate: {
			validator: v => {
// 返回布尔值
// true 验证成功
// false 验证失败
// v 要验证的值
return v && v.length > 4
			},
// 自定义错误信息
			message: '传入的值不符合验证规则'
		}
	}
});

const Post = mongoose.model('Post', postSchema);

Post.create({title: 'aa', age: 10, category: 'c1ss', author: 'bd'})
	.then(result => console.log(result))
	.catch(error => {
// 获取错误信息对象
const err = error.errors;
// 循环错误信息对象
for (var attr in err) {
// 将错误信息打印到控制台中
console.log(err[attr]['message']);
		}
	})
  1. 集合关联

populate

代码语言:javascript
复制
// 引入mongoose第三方模块 用来操作数据库
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: {
type: mongoose.Schema.Types.ObjectId,
		ref: 'User'
	}
});
// 用户集合
const User = mongoose.model('User', userSchema);
// 文章集合
const Post = mongoose.model('Post', postSchema);

// 创建用户
// User.create({name: 'itheima'}).then(result => console.log(result));
// 创建文章
// Post.create({titile: '123', author: '5d4f11e99980a325e89958b4'}).then(result => console.log(result));
Post.find().populate('author').then(result => console.log(result))
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 web前端基地 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 MongoDB
腾讯云数据库 MongoDB(TencentDB for MongoDB)是腾讯云基于全球广受欢迎的 MongoDB 打造的高性能 NoSQL 数据库,100%完全兼容 MongoDB 协议,支持跨文档事务,提供稳定丰富的监控管理,弹性可扩展、自动容灾,适用于文档型数据库场景,您无需自建灾备体系及控制管理系统。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档