当前位置:网站首页>Mongodb在node中的使用
Mongodb在node中的使用
2022-07-06 09:29:00 【社会你磊哥,命硬不弯腰】
安装mongodb
首先先认识一下这个数据库,MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
安装并配置这个数据库参考官网即可!本篇博客主要说明在该数据库与node怎样建立连接并且实现增删改查等主要功能!
安装mongoose
我们在与数据库建立连接的过程中使用的是mongoose这个第三方包!
$ npm install mongoos
设置集合结构,字段名称是表结构中的属性名称,约束的目的是保证没有脏数据!
var Schema = mongoose.Schema;
var userSchame = new Schema({
username: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
mobelphone: {
type: Number
}
})
连接数据库,连接的是test数据库!
mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true });
将文档结构发布为模型,mongoose会将第一个大写字符串的作为数据库的名称,并将其小写字符串复数作为一个集合!
var User = mongoose.model('User', userSchame);
var admin = new User({
username: "gaochi",
age:18,
mobelphone: "12345678"
});
增
admin.save(function (err, ret) {
if (err) {
console.log("wrong!")
}
else {
console.log(ret);
}
})
删
User.remove(
{
name: 'renjialei' },
function (err, ret) {
if (err) {
console.log("删除失败");
} else {
console.log("删除成功");
}
})
改
User.updateMany({
username: 'renjialei' }, {
age: 17 }, function (err, ret) {
if (err) {
console.log("更改失败");
} else {
console.log("更改成功");
}
})
查
User.find(
//这块写的是我们的查询条件!
/* { username: 'gaochi' }, */
function (err, ret) {
if (err) {
console.log('err!');
} else {
console.log(ret);
}
})
最后附加上几个mongodb的简单命令
mongod //开启数据库!
mongo //开启数据库之后,该命令可以将数据库和客户端连接起来!
show dbs //展示数据库集合名称
use (collections)//进入数据库集合,没有则创建!
db.(collections).find() //查找集合中的数据!
show collections //展示数据库里面的所有集合!
db.(collections).insertOne({
}) //向数据库里面添加数据!
补充一个非常重要的知识点,mongod命令可以启动mongodb程序,必须在启动命令的那个盘的根目录下创建一个/data/db的文件夹,保存我们的数据,而不是在下载mongodb的那个目录下去创建文件夹!mongo命令则在我们的项目文件下去使用,将项目和数据库连接起来!
边栏推荐
- 亮相Google I/O,字节跳动是这样应用Flutter的
- TypeScript基本操作
- 字节跳动技术新人培训全记录:校招萌新成长指南
- Solve the problem of intel12 generation core CPU [small core full, large core onlookers] (win11)
- 我在字节跳动「修电影」
- 视频压缩编码和音频压缩编码基本原理
- 字节跳动新程序员成长秘诀:那些闪闪发光的宝藏mentor们
- Error occurred during initialization of VM Could not reserve enough space for object heap
- ~86m rabbit practice
- FLV格式详解
猜你喜欢
随机推荐
腾讯面试算法题
TCP的三次握手和四次挥手
SQL quick start
LeetCode 1447. Simplest fraction
力扣leetcode第 280 场周赛
Typescript basic operations
Redis standalone startup
Chapter 1 overview of MapReduce
~77 linear gradient
Introduction to microservices
Shell_ 02_ Text three swordsman
~70 row high
LeetCode 1640. Can I connect to form an array
~74 JD top navigation bar exercise
Monomer application concept
LeetCode 1638. Count the number of substrings with only one character difference
7-4 harmonic average
Soft music -js find the number of times that character appears in the string - Feng Hao's blog
SQL快速入门
ByteDance open source Gan model compression framework, saving up to 97.8% of computing power - iccv 2021









