---
# System prepended metadata

title: 9 MongoDB

---

---
# 9 MongoDB
---
# 9 MongoDB

[進首頁創專案](https://cloud.mongodb.com/v2/62a83ee8fe15fd039ee7f421#security/network/accessList)

![](https://i.imgur.com/pCkvgtU.png)
![](https://i.imgur.com/2n6I6wf.png)

取得連結:
![](https://i.imgur.com/1jwvhUl.png)
![](https://i.imgur.com/ROE2S12.png)



---
## 插件
npm i dotenv express mongoose validator
npm i -D nodemon eslint

F1 eslint 

起手式
```javascript=
import 'dotenv/config'
import express from 'express'
import mongoose from 'mongoose'

mongoose.connect(process.env.DB_URL)

const app = express()

app.use(express.json())

app.listen(process.env.PORT || 4000, () => {
  console.log('in')
})
```
express:開網站可接收資料
mongoose:用簡單方式跟mongoDB溝通

![](https://i.imgur.com/o0vYnFR.png)
![](https://i.imgur.com/MT53Gxb.png)
![](https://i.imgur.com/p4OWFLT.png)

去掉test+補上password 貼上
![](https://i.imgur.com/de2rtYh.png)

---
初始node.js 專案
https://hackmd.io/zxeqQuckTn-zBY3uj4lC3g#9-MongoDB

npm i dotenv express mongoose

 index.js

```javascript=
import 'dotenv/config'
import express from 'express'
import mongoose from 'mongoose'

mongoose.connect(process.env.DB_URL)
const app = express()

app.listen(process.env.PORT || 4000, () => {
  console.log('in')
})

```

.env
![](https://i.imgur.com/20Xoxp6.png)
![](https://i.imgur.com/VCuthXu.png)
![](https://i.imgur.com/tt5XsJE.png)

---
[驗證用](https://www.npmjs.com/package/validator)
npm i validator
import { isEmail } from 'validator'
![](https://i.imgur.com/X01Mg0n.png)

![](https://i.imgur.com/TdjqBRQ.png)

![](https://i.imgur.com/SFwbwKh.png)

![](https://i.imgur.com/IEat2cn.png)

```javascript=
// .populate('user', 'account')
// 自動抓 user 欄位對應的 ref 資料，只取 account 欄位
// .populate('user', '-account') 指忽略account
users.find().populate('products.product').populate('user', 'account')
```

[之後要各種語法從這找~](https://mongoosejs.com/docs/api/model.html)

## 相關技術介紹
https://blog.toright.com/posts/4537/mongodb-schema-%E8%A8%AD%E8%A8%88%E6%8C%87%E5%8D%97-part-ii-%E5%8F%8D%E6%AD%A3%E8%A6%8F%E5%8C%96%E7%9A%84%E5%A8%81%E5%8A%9B.html
