跟我學(xué) node + MongoDB
一、MongoDB數(shù)據(jù)庫安裝
1.1 下載與安裝
下載地址:https://www.mongodb.com/download-center/community

MongoDB可視化操作軟件,是使用圖形界面操作數(shù)據(jù)庫的一種方式。
下載地址:https://www.mongodb.com/try/download/compass


這里都是一些傻瓜式安裝,不懂得話百度下就差不多了。
1.2 數(shù)據(jù)庫相關(guān)概念說明
在一個數(shù)據(jù)庫軟件中可以包含多個數(shù)據(jù)倉庫,在每個數(shù)據(jù)倉庫中可以包含多個數(shù)據(jù)集合,
每個 數(shù)據(jù)集合中可以包含多條文檔(具體的數(shù)據(jù))。

二、MongoDB的搭建
- 使用Node.js操作MongoDB數(shù)據(jù)庫需要依賴Node.js第三方包mongoose
- 使用npm install mongoose命令下載
1. MongoDB的連接與停止
// 啟動 MongoDB 服務(wù)
net start mongodb
// 停止 MongoDB 服務(wù)
net stop mongodb
// 安裝 mongoose 第三方包 ,用于 node 操作 MongoDB 數(shù)據(jù)庫
cd 進(jìn)入 項目目錄,安裝 -->
npm install mongoose
2.1 node.js 連接MongoDB數(shù)據(jù)庫
使用mongoose提供的connect方法即可連接數(shù)據(jù)庫。
在MongoDB中不需要顯式創(chuàng)建數(shù)據(jù)庫,如果正在使用的數(shù)據(jù)庫不存在,MongoDB會自動創(chuàng)建。
mongoose.connect('mongodb://localhost/playground')
.then(() => console('連接數(shù)據(jù)庫成功'))
.catch(err => console('連接數(shù)據(jù)庫失敗',err));
完整寫法:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{useNewUrlParser:true, useUnifiedTopology: true})
.then(() => console.log('連接數(shù)據(jù)庫成功'))
.catch(err => console.log('連接數(shù)據(jù)庫失敗'));
三、MongoDB 增刪改查操作
3.1 創(chuàng)建集合
創(chuàng)建集合分為兩步,一是對對集合設(shè)定規(guī)則,二是創(chuàng)建集合,創(chuàng)建mongoose.Schema構(gòu)造函數(shù)的實例即可創(chuàng)建集合。
如果集合中沒有數(shù)據(jù)(文檔),數(shù)據(jù)庫中是不會顯示該集合的。
// 設(shè)定集合規(guī)則
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
});
// 創(chuàng)建集合并應(yīng)用規(guī)則
const Course = mongoose.model('Course', courseSchema); // courses
3.2 創(chuàng)建文檔
創(chuàng)建文檔實際上就是向集合中插入數(shù)據(jù)。
3.2.1 方式1
分為兩步:
① 創(chuàng)建集合實例。
② 調(diào)用實例對象下的save方法將數(shù)據(jù)保存到數(shù)據(jù)庫中。
// 創(chuàng)建集合實例
const course = new Course({
name: 'Node.js course',
author: '講師',
tags: ['node', 'backend'],
isPublished: true
});
// 將數(shù)據(jù)保存到數(shù)據(jù)庫中
course.save();
3.2.2 方式2
Course.create({
name: 'JavaScript基礎(chǔ)', author: '講師', isPublish: true}, (err, doc) => {
// 錯誤對象
console.log(err)
// 當(dāng)前插入的文檔
console.log(doc)
});
// 另一種寫法
Course.create({name: 'JavaScript基礎(chǔ)', author: '講師', isPublish: true})
.then(doc => console.log(doc))
.catch(err => console.log(err))
3.3 MongoDB 數(shù)據(jù)庫導(dǎo)入數(shù)據(jù)
mongoimport –d 數(shù)據(jù)庫名稱 –c 集合名稱 –file 要導(dǎo)入的數(shù)據(jù)文件
找到mongodb數(shù)據(jù)庫的安裝目錄,將安裝目錄下的bin目錄放置在環(huán)境變量中。
如果找不到 mongoimport文件 --> 原因: mongoimport mongoexport mongodump mongorestore 等工具,作為 mongodb database tools 提供了單獨的下載入口 https://www.mongodb.com/try/download/database-tools?tck=docs_databasetools

將下載好的 文件 解壓到mongodb的目錄下,然后配置環(huán)境變量。我的目錄是 G:\MongoDB_new\database-tools\tools\bin

配置成功后,即可使用 mongoimport 命令 ,比如 :
mongoimport -d playground -c users --file .\user.json
