lemooljiang avatar

Mongoose操作数据库 / 网络研习社#80

lemooljiang

Published: 07 Apr 2023 › Updated: 07 Apr 2023

Mongoose操作数据库 / 网络研习社#80

mongoose.jpg

https://mongoosejs.com/

英文手册 |
中文文档

安装和连接

cnpm install mongoose --save   //"mongoose": "^7.0.3"

import mongoose from 'mongoose'

mongoose.connect('mongodb://localhost:27017/test')
mongoose.connect('mongodb://admin:562589@localhost:27017/test?authSource=admin')  //开启了权限,用户名和密码
.then(() => console.log('Connected!'))
.catch(error => console.log(44, error))

//其它的监听形式
mongoose.connection.on('connected', res => {
  console.log(123, res)
}) 
mongoose.connection.on('error', err => {
  logError(err)
})

增删改查

import mongoose from 'mongoose'

// 1. 连接数据库
// 指定连接的数据库可以不存在,当你插入第一条数据之后就会自动被创建出来
mongoose.connect('mongodb://localhost/test')

// 2. 设计文档结构(表结构)
// 字段名称就是表结构中的属性名称
// 约束的目的是为了保证数据的完整性,不要有脏数据
const { Schema } = mongoose
const userSchema = new Schema({
  username: {
    type: String,
    required: true // 必须有
  },
  password: {
    type: String,
    required: true
  },
  email: {
    type: String
  }
})

const blogSchema = new Schema({
  title: String, // String is shorthand for {type: String}
  author: String,
  body: String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs: Number
  }
})

// 3. 将文档结构发布为模型
//    mongoose.model 方法就是用来将一个架构发布为 model
//    第一个参数:传入一个大写名词单数字符串用来表示你的集合名称
//    mongoose 会自动将大写名词的字符串生成 小写复数 的集合名称
//    例如这里的 User 最终会变为 users 集合名称
//    第二个参数:架构 Schema
//    返回值:模型构造函数
const User = mongoose.model('User', userSchema)  //关联 users 的集合

//创建集合Cat,会自动集合cats
const Cat = mongoose.model('Cat', { name: String })


// 4. 当我们有了模型构造函数之后,就可以使用这个构造函数对 users 集合中的数据增删改查
//新增数据
const admin = new User({
    username: 'jiang',
    password: '55555',
    email: 'admin@admin.com'
  })
admin.save()
.then((res) => console.log('新增成功', res))
.catch(error => console.log(44, error))

//查找数据
User.find()  //查找所有数据
.then((res) => console.log('查找成功', res))
.catch(error => console.log(44, error))

//增加查找条件
or() 
limit(1) 
sort()   
skip()
User.find()//查询全部
  .or([{gender:2}])//查询gender为2的数据
  .sort({_id:'desc'})//倒序排列数据, 或sort({_id: -1}),asc正序  
  .limit(2)//展示两条
  .skip(2)//跳过前两个


User.find({
    username: 'jiang'  //查询条件
})
.then((res) => console.log('查找成功', res))
.catch(error => console.log(44, error))

User.findOne({
    username: 'jiang' 
})
.then((res) => console.log('查找成功', res))
.catch(error => console.log(44, error))

//删除数据  deleteOne deleteMany
User.deleteOne({
    username: 'jiang'
})  
.then((res) => console.log('删除成功', res))
.catch(error => console.log(44, error))

//更新数据
let res = await User.findOne({username:'jiang'})
res.set({username:'li'})
res.save()

User.findByIdAndUpdate('5a001b23d219eb00c8581184', {
  username:'li'
}, function (err, ret) {
  if (err) {
    console.log('更新失败')
  } else {
    console.log('更新成功')
  }
})

后端nodejs操作MongoDB一般会采用Mongoose的方案,因其简洁和便利。它的增删改查也更接近自然语言,没有SQL那么难理解,优势还是蛮大的。

运行MongoDB做数据库,心里还是有点不乐意。但是目前还没有理想的区块链替代方案,就是layer2也还是太贵了,不适合开发者。倒是Evmos可以考查下,自已做见证人运行个链如何?

Leave Mongoose操作数据库 / 网络研习社#80 to:

Written by

Designer , Poet , Technology enthusiasts

Read more #cn posts


Best Posts From lemooljiang

We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From lemooljiang