建立 API
建立 Controller
接著就來建立兩個 Controller productController
和 manufacturerController
controllers/manufacturer.js
這個 Controller 管理製造商(manufacturers)資料的操作,回頭看看上面路由中的方法是不是都找到了呢?
開頭導入了之前在 Model 中定義過的 ManufacturerModel
,這是 mongoose 提供給我們操作資料庫的介面。通過 Model 上定義的一系列指令來對 Manufacturer 做資料操作
const Model = require('../model');
const { Manufacturer } = Model;
const manufacturerController = {
all(req, res) {
Manufacturer.find({})
.exec((err, manfacturers) => res.json(manfacturers))
},
byId(req, res) {
const idParams = req.params.id;
Manufacturer
.findOne({ _id: idParams })
.exec((err, manufacturer) => res.json(manufacturer));
},
create(req, res) {
const requestBody = req.body;
const newManufacturer = new Manufacturer(requestBody);
newManufacturer.save((err, saved) => {
Manufacturer
.findOne({ _id: newManufacturer._id })
.exec((err, manfacturer) => res.json(manfacturer))
})
},
update(req, res) {
const idParams = req.params.id;
let manufacturer = req.body;
Manufacturer.updateOne({ _id: idParams }, { ...manufacturer }, (err, updated) => {
res.json(updated);
})
},
remove(req, res) {
const idParams = req.params.id;
Manufacturer.findOne({ _id: idParams }).remove( (err, removed) => res.json(idParams) )
}
}
module.exports = manufacturerController;
controllers/product.js
而在 productController 中基本上與上方 manufacturerController 概念一致
const Model = require('../model');
const { Product } = Model;
const productController = {
all(req, res) {
Product.find({})
.populate('manufacturer')
.exec((err, products) => res.json(products))
},
byId(req, res) {
const idParams = req.params.id;
Product
.findOne({ _id: idParams })
.populate('manufacturer')
.exec((err, product) => res.json(product));
},
create(req, res) {
const requestBody = req.body;
const newProduct = new Product(requestBody);
newProduct.save((err, saved) => {
Product
.findOne({ _id: newProduct._id })
.populate('manufacturer')
.exec((err, product) => res.json(product))
})
},
update(req, res) {
const idParams = req.params.id;
const product = req.body;
console.log('idParams', idParams);
console.log('product', product);
Product.updateOne({ _id: idParams }, { ...product }, (err, updated) => {
res.json(updated);
})
},
remove(req, res) {
const idParams = req.params.id;
Product.findOne({ _id: idParams }).remove( (err, removed) => res.json(idParams) )
}
}
module.exports = productController;
完成後存擋,在終端機執行 npm start
先確定是你的 mongoDB 要是開著的,可以使用指令
mongo
看能不能進入 mongo 的指令列中,如果忘記怎麼開啟可以回到前面 連接 MongoDB 章節複習
留言
張貼留言