• 启动数据库:打开命令行,执行:net start mongodb、mongod
  • 停止数据库:打开命令行,执行:net stop mongodb、mongod

先下载第三方模块mongoose :npm i mongoose
连接案例:

const mongoose = require('mongoose')
const dburl = 'mongodb://localhost:27017/dbname'
mongoose.connect(dburl).then(()=>{
    console.log('连接成功');
    
}).catch(()=>{
    console.log('连接失败');
    
})

如果连接的数据库不存在,mongodb会在第一次插入数据的时候自动给我们创建

接下来=>创建集合·增(和MySQLmysql创建表一样)
创建集合主要分为俩步:

创建集合规则

  • 应用集合规则,创建集合

=>创建文档(相当于像表中插入数据)
也分俩步:

  • new 集合() 创建文档实例
  • 调用save方法保存

案例:

//创建集合规则
const usersname = new mongoose.Schema({
    name: { type: String, required: true },
    createTime: { type: Date, default: Date.now },
    sex: String,
    avatar: String,
    vip: Boolean,
})
//应用集合规则,创建集合
const User = mongoose.model('User',usersname,'User')
//创建文档实例
const y = new User({
    name:'哈哈哈哈',
    sex:'男',
    avatar:'lol',
    vip:true
})
//调用save方法保存
y.save()

(Schema 是什么
在 Mongoose 中,所有数据都由一个 Schema 开始创建。每一个 schema 都映射到一个 Mongodb 的集合(collection),并定义了该集合(collection)中的文档(document)的形式)

  • 插入文件的另一种方式:可以使用集合构造函数的create方法来插入文档(推荐用这个),案例:
// [ 回调函数形式
User.create({
  name: 'ww',
  age: 19,
  isMarry: true
}, (err, user) => {
  cnosole.log(user)
})
// ] 回调函数形式

// [ Promise 形式
User.create({
  name: 'ww',
  age: 19,
  isMarry: true
}).then(doc => {
  console.log(doc)
})
// ] Promise 形式

// [ async await 形式 (推荐)
;(async () => {
  const ww = await User.create({
    name: 'zl',
    age: 59,
    isMarry: true
  })
  console.log(ww)
})()
// ] async await 形式

向数据库中导入数据:

导入数据:mongoimport -d 数据库名称 -c 集合名称 --file 要导入的文件路径
=>删除数据操作
删除单个:

User.findOneAndDelete({ 条件 }).then...
  • 返回的是被删除的文档 如果匹配到多条,删除第一条 删除多个:
User.deleteMany({}).then(result => console.log(result))

!!!一定不要忘记带条件,如果不带就是无条件删除该集合中所有数据

返回值是本次删除操作的信息对象,形如:{ n: 2, ok: 1, deletedCount: 2 }

  • n:表示匹配的条数
  • ok:表示本次删除操作是否执行成功,1:成功,0:失败
  • deletedCount:代表已经被删除的条数

补充说明:当本次删除操作异常时,n和deletedCount就有可能不一致
=>修改数据
更新单个:

User.updateOne({name: '李四'}, {age: 120, name: '李狗蛋'}).then(result => console.log(result))

返回值是更新信息对象,形如:{ n: 1, nModified: 1, ok: 1 }

  • n:表示匹配的条数
  • nModified:表示已经更新的条数
  • ok:表示本次更新操作是否执行成功,1:成功,0:失败
User.updateMany({}, {age: 300}).then(result => console.log(result))

返回值和updateOne一样

=>查询数据

  • find():查找多个,返回的是数组,不管有多少个,返回的都是数组
  • findOne():查找一个,返回的是一个文档,如果匹配到多条,返回第一条

共同点:它们都返回Promise对象,既然返回的是Promise对象,那么就推荐使用async/await关键字去调用,都可以带查询条件
大于、小于:

User.find({ age: { $gt: 18, $lt: 40 } }).then(users => console.log(users))

包含:

User.find({ hobbies: { $in: ['敲代码'] } }).then(users => console.log(users))

筛选字段(_id会默认带上,如果不要在前面加个-):

User.find().select('name age').then(users => console.log(users))

排序:

// 升序
User.find().sort('age').then(users => console.log(users))
// 降序
User.find().sort('-age').then(users => console.log(users))

分页,跳过n条(skip),查n条(limit):

// 获取第4页的数据
User.find().skip(3 * 10).limit(10).then(users => console.log(users))

多集合联合查询(集合关联)

  • 通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
// 用户集合
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } })); 
// 文章集合
const Post = mongoose.model('Post', new mongoose.Schema({
    title: { type: String },
    // 使用ID将文章集合和作者集合进行关联
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}));
//联合查询
Post.find()
      .populate('author')
      .then((err, result) => console.log(result));

Mongoose验证

在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。

常见的验证规则:

  • required: true 必传字段
  • minlength:3 字符串最小长度
  • maxlength: 20 字符串最大长度
  • min: 2 数值最小为2
  • max: 100 数值最大为100
  • enum: [‘html’, ‘css’, ‘javascript’, ‘node.js’]
  • trim: true 去除字符串两边的空格
  • validate: 自定义验证器
  • default: 默认值

在catch中获取错误信息

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']);
		}
	})