使用node创建一个服务,提供数据交互接口;数据库选用MongoDB。
安装
首先官网下载地址(https://www.mongodb.com/download-center/community)
很是无语,一眼找不到下载的入口;找了半天,终于在这边搜索下载、选择第一个才找到:
一路点击安装即可。默认目录会在C:
盘下;我安装的目录是(之后所有的目录都以你安装的目录)
然后创建data
目录用于存储数据库表之类的\data\db
;
进入bin
目录,命令行启动执行:
看到一直打印完毕,没有退出说明启动成功了。
通过点击/bin/mongo.exe
连接启动的数据库,端口号27017
:
执行命令db
查看当前连接的数据库为test
;使用use
命令切换数据库,没有会自动创建:
基础概念
mongoDB
非关系型数据库,是键值对对象数据的集合。
关系型数据库 | 数据关系 | |
---|---|---|
数据库 | 数据库 | |
表(table) | 集合(collection) | |
记录(record) | 文档(document) | |
字段 | 字段 |
说明:
- 文档中新插入一条数据默认主键
_id
; - 文档中区分大小写;
- 文档中不能有重复的键;
- 数据类型:
String
/Integer
/Boolean
/Array
/Object
/Date
…
一些原生命令:
show dbs
展示所有的数据库;db
展示当前连接的数据库;use **
手动切换链接数据库,没有则会自动创建;db.dropDatabase()
删除当前连接的数据库;db.createCollection("**",opt)
创建一个集合;show collections
展示当前连接的数据库中的集合,db.**.drop()
删除一个集合;db.**.insert()/update()/remove()/find()
增删改查集合数据;
数据库连接
参考:菜鸟教程
教程中展现的使用mongodb
模块管理数据库,通过创建MongoClient
对象 ,连接MongoDB进行操作。
通过使用连接驱动程序,选用Mongoose
,封装底层,展现更加有好的操作、概念理解。
npm install mongoose
安装到项目依赖。
mongoose API 文档 ,看起来有点费劲,最后查看了【CNode】社区开源的代码。
建立连接并创建一个文档模型:
const mongoose = require("mongoose");
// 数据库配置文件
const dbConfig = require("../config/db");
// 连接 ,dbConfig.url : mongodb://localhost/zkuan
// 没有设置密码
mongoose.connect(dbConfig.url,{
poolSize:20,
useCreateIndex:true,
useNewUrlParser:true
},function(err){
if(err) console.error("conn error:",err.message);
});
let articleSchema = mongoose.Schema({
title:{type:String}, // 标题
desc:{type:String}, // 简述
createTime:{type:Date,default:Date.now}, // 创建时间
updateTime:{type:Date,default:Date.now}, // 更新时间
author:{type:String}, // 发布者
origin:{type:String}, // 信息来源
content:{type:String}, // 文章内容
});
// 在保存之前设定更新时间
articleSchema.pre('save',function(next){
let now = new Date();
this.updateTime = now;
next();
});
exports.Article = mongoose.model('article',articleSchema);
测试使用,按照API提供的方法进行操作:
// 导入Article 集合对象;
var articleModel = require("../model/Article").Article;
// 创建文档数据
let article = new articleModel();
article.title = "测试";
article.desc = "测试数据";
article.author = "admin";
article.content = "测试数据";
// 保存数据
article.save();
// 查询数据
articleModel.findOne({author:"admin"},function(err,article){
if(err) return next(err);
if(!article){
res.render404("此文章不存在");
}
console.log(article);
// res.render('index', { title: article.content });
});
最终打印结果:
使用可视化操作界面
通过使用可视化页面MongoDB Compass
来管理MongoDB数据库;
至此,Node与MongoDB数据库简单的交互完成。