我对 MongoDB的认识

本文介绍了MongoDB的启动、关闭、连接数据库的方法,以及在Node.js环境中使用MongoDB的基本步骤,包括如何通过mongodb包和mongoose进行数据操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

启动和关闭数据库:

启动:使用mongod 命令行,(如果是第一次执行该命令,需要手动新建一个/data/db),会默认执行mongod目录下的/data/db作为自己数据存储目录;

如果想要修改默认的数据存储目录,可以:

mongod --dbpath=数据存储目录路径

停止:

在开启服务的控制台直接ctrl+c就可以了,或者直接关闭服务台;

连接数据库:

(确保已经开启服务台),使用mongo命令行,默认链接mongodb服务

退出:在链接状态输入exit退出,

基本命令:

show dbs查看所有的数据显示
use 数据库名称切换到指定的数据库(如果没有,会新建)
db查看当前操作的数据库
插入数据 

在node中如何操作mongodb:

1.使用mongodb包来操作;

2.基于第三方包mongoose(安装:npm i mongooes);

使用步骤:

1.链接数据库

mongoose.connect('mongodb://localhost/数据库名称')

2.设计文档结构(表结构)

var userSchema = new Schema({
  username: {
    type: String,
    required: true // 必须有
  },
  password: {
    type: String,
    required: true
  },
  email: {
    type: String
  }
})

3.将文档结构发布为模型

mongoose.model 方法就是用来将一个架构发布为 model
第一个参数:传入一个大写名词单数字符串用来表示你的数据库名称
             mongoose 会自动将大写名词的字符串生成 小写复数 的集合名称
             例如这里的 User 最终会变为 users 集合名称
第二个参数:架构 Schema

返回值:模型构造函数
var User = mongoose.model('User', userSchema)

4.有了模型之后,就可以增删改查了

  1. 增加
var admin = new User({
  username: 'zs',
  password: '123456',
  email: 'admin@admin.com'
})
//数据持久化保存:
admin.save(function (err, ret) {
  if (err) {
    console.log('保存失败')
  } else {
    console.log('保存成功')
    console.log(ret)
  }
})

2.查询

//查询所有
User.find(function (err, ret) {
  if (err) {
    console.log('查询失败')
  } else {
    console.log(ret)
  }
})
//按照参数查询所有
User.find({
  username: 'zs'
}, function (err, ret) {
  if (err) {
    console.log('查询失败')
  } else {
    console.log(ret)
  }
})
//按照条件单个查询,返回对象
User.findOne({
  username: 'zs'
}, function (err, ret) {
  if (err) {
    console.log('查询失败')
  } else {
    console.log(ret)
  }
})

3.删除

User.remove({
  username: 'zs'
}, function (err, ret) {
  if (err) {
    console.log('删除失败')
  } else {
    console.log('删除成功')
    console.log(ret)
  }
})

4.更新

User.findByIdAndUpdate('5a001b23d219eb00c8581184', {
  password: '123'
}, function (err, ret) {
  if (err) {
    console.log('更新失败')
  } else {
    console.log('更新成功')
  }
})
//第一个参数是:id
//第二个参数是:更新内容
//第三个参数:回调函数

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值