为编程爱好者分享易语言教程源码的资源网
好用的代理IP,游戏必备 ____广告位招租____ 服务器99/年 ____广告位招租____ ____广告位招租____ 挂机,建站服务器
好用的代理IP,游戏必备 ____广告位招租____ 服务器低至38/年 ____广告位招租____ ____广告位招租____ 挂机,建站服务器

网站首页 > 数据库 > MongoDB 正文

Mongodb 基础操作简介(mongodb 入门)

三叶资源网 2022-06-26 08:09:17 MongoDB 472 ℃ 0 评论

连接数据库

mongoose.connect(url, options).then().catch()

创建集合规则

const collection = new mongoose.Schema({
	name: String,
	age: Number
})

使用规则创建集合

 // users
const User = mongoose.model('User', collection)

创建数据

const user = new User({
	name: 'Tom',
	age: 32
})

保存

user.save()

// 向集合中插入文档
User.create({ name: 'TOM', age: 22 }, (err, docs) => {})
User.create({ name: 'TOM', age: 22 }).then().catch()

//mongodb数据库导入数据
mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件

// $in 包含
User.find({ address: {$in: ['四川']} }).then()

// 查询的字段  -字段名(不想查询的字段) 
User.find().select('name age -address').then()

// sort: 排序 sort('age') 升序排序 sort('-age') 降序

// 删除单个,返回删除的数据
User.findOneAndDelete({}).then(res)

// 删除多个
User.deleteMany({})

// 更新单个
User.updateOne({查询条件}, {修改条件}).then()

// 更新多个
User.updateMany({查询条件}, {修改条件}).then()

验证

const user = new User({
	name: {
		type: String,
		required: [true, '请输入姓名'],
		minlength: [2, 姓名长度不能小于2],
		maxlength: 5,
		trim: true // 去掉空格
	},
	age: {
		type: Number,
		min: 10,
		max: 88
	},
	date: {
		type: Date,
		default: Date.now // 默认值
	},
	category: {
		type: String,
		// 当前字段可拥有的值
		enum: ['Java', 'Html', 'Vue', 'React'],
		// 或者
		enum: {
			values: ['Vue', 'React'],
			message: '字段值不符合规则'
		}
	},
	author: {
		type: String,
		validate: {
			// 自定义验证
			validator: value => {
				return value && value.length > 4
			},
			message: '格式不正确'
		}
	}
})

// 集合关联
const User = mongoose.model('User', new mongoose.Schema({
	name: {
		type: String
	}
}))

const Post = mongoose.model('Post', new mongoose.Schema({
	title: { type: String },
	author: {
		// id将文章集合与用户集合进行关联
		type: mongoose.Schema.Types.ObjectId,
		ref: 'User'
	}
}))

// 联合查询
Post.find().populate('author').then().catch()

Tags:

来源:三叶资源网,欢迎分享,公众号:iisanye,(三叶资源网⑤群:21414575

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

百度站内搜索
关注微信公众号
三叶资源网⑤群:三叶资源网⑤群

网站分类
随机tag
鼠标指针特性软件源码采集网页图片源码例程算法模块源码火山移动百度AI易语言与PHP交互画图形按钮快手did获取代码编辑框代码框自绘QQ授权登陆订单监控EtorchRAR注释cleverQQ机器人插件5sing网站DZ论坛post精易论坛post登录
最新评论