最近開始接觸到資料庫的概念,mongoose真是學得一個頭兩個大,隨著Node越學越多,也更加考驗自己JS的基礎,這次的問題是來自實作AC作業時所碰到的窘境,助教點出了object.assign可以更簡單的解決問題! 首先我們先看一下原始問題,接著會帶入我原先的解法,最後利用assign來達成。
問題描述
現在我欲將表單內的所有資料存進我寫好的model中,最後再將資料存進資料庫。
model中有共有7個必填的值。 如下
//model.js
const restaurantSchema = new Schema({
name: {
type: String,
required: true
},
rating: {
type: Number,
required: true
},
image: {
type: String,
required: true
},
location: {
type: String,
required: true
},
phone: {
type: String,
required: true
},
description: {
type: String
},
category: {
type: String
}
})
課程解法
router.post('/', (req, res) => {
const restaurant = new Restaurant({
name:req.body.name,
phone:req.body.phone
//以下以此類推
})
for (let i in req.body) {
restaurant[i] = req.body[i]
}
restaurant.save(err => {
if (err) return console.log(err);
res.redirect('/')
})
})
想像一下今天model內的欄位變成數十甚至數百,這樣慢慢打要打到什麼時候啊!!!
於是當時的我打算用for in 迴圈來解決,的確是很快速地解決了問題。
原始解法
const restaurant = new Restaurant()
for (let i in req.body) {
restaurant[i] = req.body[i]
}
Object.assign
其實這不是我第一次使用assign了,在最初的幾篇文章中就有這樣的紀錄,但我當時的用法是用在新增物件上的資料。這邊還是先複習一下基本語法
Object.assign(target, ...sources)
其中target指向你想要接收資料的物件,sources則放入資料的來源。
舉個例子來說
//模仿資料庫的model 做一個物件建構子
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
//建立一個實例
const john = new Person()
//將收到的數值存進實例中
Object.assign(john,{
firstName:'John',
lastName:'Chen',
age:25,
eyeColor:'blue'
})
//測試輸出結果
console.log(john.age) //25
了解基本語法後,要處理這樣的題目就變得容易許多了。
const restaurant = new Restaurant() Object.assign(restaurant, req.body) //下略
如何?利用object.assign可以簡單的完成淺層複製,對於這樣的表單資料處理再合適不過了!