启动和关闭数据库:
启动:使用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.有了模型之后,就可以增删改查了
- 增加
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
//第二个参数是:更新内容
//第三个参数:回调函数