Skip to content

Home

設置 MongoDB 與 Koa.js

我正在建設一個 Koa.js 服務器,並需要將其連接到 MongoDB 以儲存和檢索數據。以下是如何在幾個簡單的步驟中實現這一點:

步驟1:初始化 Koa 應用程序之前連接到數據庫

const initDB = require("./database")

initDB()

const app = new Koa()

database.js 中,導入 mongoose。同時確保使用 npm install --save mongoose 進行安裝。Mongoose 是一個物件數據建模(ODM)庫。

const mongoose = require("mongoose")
import { connectionString } from "./conf/app-config"

const initDB = () => {
  mongoose.connect(connectionString)

  mongoose.connection.once("open", () => {
    console.log("Connected to the database")
  })

  mongoose.connection.on("error", console.error)
}

module.exports = initDB

接下來,為您的連接字符串創建配置:

export const connectionString =
  "mongodb+srv://" +
  secret.mongodb.username +
  ":" +
  secret.mongodb.password +
  "@xxxxxx.mongodb.net/test?retryWrites=true&w=majority"

您可以運行本地 MongoDB 實例,或者使用 MongoDB Atlas 並將其託管在 AWS 雲上。您會在那裡找到包含在配置文件中的連接字符串。

步驟2:在 Koa 中創建一個 Schema

例如,讓我們在 /models/users.js 中創建一個用戶模式。

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const UserSchema = new Schema({
  username: String,
  email: String,
  picture: String,
})

module.exports = mongoose.model("User", UserSchema)

步驟3:創建一個服務來查詢數據

假設我們有一個 /service/user.service.js

import User from "../models/users"

export const getUserFromDb = async username => {
  const data = await User.findOne({ username })
  return data
}

export const createUserInDb = async user => {
  const newUser = new User(user)
  await newUser.save()
  return user
}

步驟4:在 Koa 控制器中調用服務

例如,假設我們有一個 /controller/user.controller.js

    import { getUserFromDb, createUserInDb } from '../service/user.service';

    static async getUser(ctx) {
      const user = await getUserFromDb(ctx.query.username);
      ctx.body = user;
    }

    static async registerUser(ctx) {
      const user = await createUserInDb(ctx.request.body);
      ctx.body = user;
    }

最後,您可以使用控制器註冊路由。現在,您應該能夠看到數據被存儲在數據庫中。如果您有任何問題,請隨時聯繫我。

Migrating Your Blog from Medium to Ghost 3.0

Ghost 3.0 has just been released (https://ghost.org/3/). I have a strong preference for Ghost over WordPress because it uses Node.js instead of PHP. Not only is Ghost open-source, but it also offers a pretty cool dark theme. So, I decided to migrate my blog away from Medium. However, the process isn't straightforward and does come with some associated costs. Here are the steps to help you navigate the migration and regain control of your content:

Step 1: Export Posts from Medium

Navigate to Settings on Medium and find the section that allows you to download your data:

Step 2: Import to WordPress.com and Export the File

Create a free account on WordPress.com. In the Import section, you'll find an option to import content from Medium:

After successfully importing your content from Medium, you can then export the file from WordPress.com:

Step 3: Import the File to WordPress.org via Plugin and Export the File

Download the open-source WordPress software from http://wordpress.org/ and run it locally using MAMP (https://www.mamp.info/en/). Copy all the WordPress files and place them in the /htdocs folder within MAMP. Start the server, and you should be able to run the local WordPress instance with MySQL installed.

Navigate to the Import section and select the option to import from WordPress:

Next, install the official Ghost plugin from https://wordpress.org/plugins/ghost/ and export your blog posts using this plugin:

Although there's an option to download the Ghost file, it didn't work for me. Try clicking on the download .json file instead.

Step 4: Import to Ghost Blog

Go to Settings and then the Labs section in Ghost, and import your file:

Fingers crossed! If all goes well, you should see all your posts from Medium now migrated to Ghost 3.0. Happy blogging :)

Migrating Your Blog from Medium to Ghost 3.0

Welcome back to "Continuous Improvement," the podcast where we explore ways to enhance our personal and professional lives. I'm your host, Victor, and in today's episode, we're diving into the exciting world of blogging platform migration. Specifically, we'll discuss how to migrate your blog from Medium to Ghost 3.0.

But before we begin, let me share why I prefer Ghost over WordPress. Ghost, unlike WordPress, is built using Node.js instead of PHP. It's not only open-source, but it also offers a sleek and stylish dark theme. So, if you're ready to regain control of your content and make the jump to Ghost, let's get started.

Step one: Exporting your posts from Medium. Head over to the Settings section on Medium's platform and locate the section that enables you to download your data. Click on it, and your post data will be exported to a file.

Moving on to step two: Importing the exported file to WordPress.com. Create a free account on WordPress.com, and within the Import section, you'll find an option to import content from Medium. Follow the prompts to successfully import your posts. Once completed, you can then export the file from WordPress.com in a format compatible with Ghost.

Step three: Importing the file to WordPress.org via a plugin. Begin by downloading the open-source WordPress software from wordpress.org. Run it locally using MAMP, a tool that allows us to set up a local server environment. Once set up, copy all the WordPress files and place them in the htdocs folder within MAMP. Start the server, and voila! You should now be able to run your WordPress instance on your local machine.

Within the WordPress dashboard, navigate to the Import section and select the option to import from WordPress. Follow the instructions to import the file you previously exported from WordPress.com.

Now, it's time to prepare for the final export. Install the official Ghost plugin from the WordPress plugin repository. With the plugin installed, you can export your blog posts using it. Though you're provided with an option to download the Ghost file, it may not work as expected. Instead, try clicking on the download .json file option as an alternative.

Step four: Importing your posts to Ghost. In your Ghost dashboard, go to the Settings tab and then navigate to the Labs section. Here, you'll find an option to import files. Select your exported file and initiate the import process. With a little luck, all your posts from Medium should now be beautifully migrated to Ghost 3.0.

And that's it! Congratulations on successfully migrating your blog from Medium to Ghost 3.0. Feel free to explore Ghost's various features and continue your blogging journey with this powerful open-source platform.

Thank you for tuning in to this episode of "Continuous Improvement." I hope you found the information valuable and that it encourages you to embrace new platforms like Ghost. Remember, continuous improvement is all about taking small steps towards a better future, both in your personal and professional endeavors. If you have any questions or suggestions for future episodes, please reach out to me through our website. Until next time, keep improving!

將您的部落格從Medium遷移到Ghost 3.0

Ghost 3.0剛剛被發佈 (https://ghost.org/3/)。我對Ghost比WordPress有強烈的偏好,因為它使用Node.js而不是PHP。Ghost不僅是開源的,還提供了非常酷的黑色主題。所以,我決定將我的部落格從Medium遷移出去。然而,該過程並不直接,也有一些相關的成本。下面是一些步驟幫助你導航遷移並重新控制你的內容:

步驟一:從Medium導出帖子

在Medium上導航到設置並找到允許您下載您的數據的部分:

步驟二:導入至WordPress.com並導出文件

在WordPress.com上創建一個免費帳戶。在導入部分,您會找到一個可以從Medium導入內容的選項:

成功從Medium導入內容後,你可以從WordPress.com導出文件:

步驟三:通過插件將文件導入至WordPress.org並導出文件

http://wordpress.org/ 下載開源的WordPress軟件並使用MAMP (https://www.mamp.info/en/) 在本地運行。複製所有的WordPress文件並將它們放在MAMP內的/ htdocs資料夾中。啟動服務器,您應該能夠運行安裝了MySQL的本地WordPress實例。

導航至導入部分,並選擇從WordPress導入的選項:

然後,從https://wordpress.org/plugins/ghost/ 安裝官方的Ghost插件,並使用此插件導出你的部落格文章:

雖然有一個下載Ghost文件的選項,但對我來說並未奏效。嘗試點選下載.json檔案。

步驟四:導入至Ghost博客

轉到設置,然後轉到Ghost中的實驗室部分,並導入您的文件:

交叉手指!如果一切順利,您應該能看到所有您從Medium導出的文章現已遷移到Ghost 3.0。祝你寫博愉快 :)

Setting Up npm Proxy in a Corporate Network

Working behind a corporate network can be challenging, as many things do not work "out of the box." A simple command like npm install might not function properly. Here's how to work through the proxy:

Assuming you've somehow managed to install node.js on your corporate laptop, locate the .npmrc file. On Windows, this is typically located at C:\Users\<your_user_id>\.npmrc, and on a Mac, it's at Users/<your_user_id>/.npmrc.

Open the file and add the following lines:

    https-proxy=http://yourcompanyproxy.com:80
    proxy=http://yourcompanyproxy.com:80
    strict-ssl=false
    registry=http://registry.npmjs.org/

Try running npm install again; it should work now!

Here's an additional tip: if you have some dependencies hosted in your corporate internal Nexus npm repository—let's say in the @npmcorp scope—run the following command to specify the correct registry URL:

    npm config set @npmcorp:registry https://your-company-nexus:80/nexus/content/repository/npm-internal

By doing this, you should be able to resolve any "dependency not found" errors. Give it a try!

Setting Up npm Proxy in a Corporate Network

Hello and welcome to "Continuous Improvement," the podcast where we explore strategies and techniques to enhance our professional lives. I'm your host, Victor, and today we'll be diving into the topic of working behind a corporate network and overcoming challenges that arise. Specifically, we'll be discussing how to successfully work with proxies when using commands like npm install.

Working within a corporate network often requires additional steps to get things up and running smoothly. For instance, commands that typically work perfectly outside the corporate environment may not function as expected within it. But fear not, because today we'll be sharing some helpful tips to work through proxy issues and ensure you can use npm install without any hiccups.

Assuming that you've already installed node.js on your corporate laptop, the first step is to locate the .npmrc file. On Windows, this file is typically found at C:\Users\<your_user_id>\.npmrc. And on a Mac, you can find it at Users/<your_user_id>/.npmrc.

Open the .npmrc file and add the following lines:

    https-proxy=http://yourcompanyproxy.com:80
    proxy=http://yourcompanyproxy.com:80
    strict-ssl=false
    registry=http://registry.npmjs.org/

These lines will help in configuring the proxy settings necessary to ensure the smooth functioning of npm install. Now, give npm install another try, and you'll see that it works seamlessly!

But wait, there's more! If you have dependencies hosted in your corporate internal Nexus npm repository, there's an additional step you can take to resolve any "dependency not found" errors. Let's say your dependencies are in the @npmcorp scope. To specify the correct registry URL, run the following command:

    npm config set @npmcorp:registry https://your-company-nexus:80/nexus/content/repository/npm-internal

By running this command, you'll ensure that the correct registry URL is used, and any "dependency not found" errors will be resolved. It's a small step that can make a big difference in your work.

So there you have it, a couple of essential tips to overcome proxy issues when working with npm install within a corporate network. By configuring the proxy settings and specifying the correct registry URL for internal dependencies, you'll be able to navigate any obstacles that come your way.

That wraps up today's episode of "Continuous Improvement." I hope you found these tips helpful and will apply them in your work environment. Remember, it's all about continuously improving our professional lives, one step at a time.

If you have any questions or specific topics you'd like us to cover, feel free to reach out to us on our website or social media channels. Don't forget to subscribe to our podcast for more insightful episodes.

Thank you for joining me today. I'm Victor, and until next time, keep striving for continuous improvement.

在企業網路中設置npm代理

在企業網路下工作可能相當有挑戰性,因為許多東西不會即刻就能運作正常。像是 npm install 等簡易指令可能都無法正常運作。以下為如何跨過代理進行工作的方法:

假設你已經成功在你所使用的企業筆記本電腦中安裝 node.js,找出 .npmrc 檔案。在Windows系統中,該檔案通常位於 C:\Users\<your_user_id>\.npmrc,而在Mac機上,該檔案則位於 Users/<your_user_id>/.npmrc

打開該檔案並加入下列行數:

    https-proxy=http://yourcompanyproxy.com:80
    proxy=http://yourcompanyproxy.com:80
    strict-ssl=false
    registry=http://registry.npmjs.org/

再試執行 npm install,它應該現在可以運作了!

附帶一提的小提示:如果你在企業內部的 Nexus npm 倉庫有一些依賴關係,例如在 @npmcorp 範疇中,運行以下標令以指定正確的倉庫 URL:

    npm config set @npmcorp:registry https://your-company-nexus:80/nexus/content/repository/npm-internal

這樣做應該就能解決任何 "依賴性未找到" 的錯誤。試試看吧!

My MBA Study Trip to Germany

Traveling involves a great deal of uncertainty and chance. Despite the delay of my flight in Helsinki, Finland, and the stress from a jet lag-induced presentation, the journey proved worthwhile as it enriched my professional management skills beyond the classroom.

The tour was filled with thought-provoking and educational talks on topics such as Germany's macroeconomics, the European Union, hidden champions, Industry 4.0, and artificial intelligence. Our visits to Wattx, a deep tech business, and the Daimler AG factory, where BMW automobiles are manufactured, were enlightening. The most significant personal takeaway from the trip is that Germany is antifragile. Although Germany was fragile during World War II, its current wealth demonstrates its antifragility.

The trip revealed that Germany has the highest number of hidden champions—companies that are either in the global top three or the number one in Europe, generate annual revenues of more than 5 million euros, and maintain a low degree of public recognition. With numerous small-to-medium enterprises (SMEs) specializing in deep technology, the German economy thrives on exports and innovation. These family-owned enterprises are clustered and decentralized across Germany rather than being concentrated in Berlin, among the 1,307 hidden champions.

From my perspective, Germany is antifragile due to its vibrant start-up scene and decentralization. Large corporations may have strong hierarchical structures and numerous regulations, but they are vulnerable due to higher turnover rates and lesser adaptability and flexibility. SMEs, on the other hand, boast lean structures that foster a high-performance culture, increased employee engagement, and a more people-oriented approach. Such antifragility also manifests in more frequent employee transfers between various functions within the business. Employees at SMEs generally have more direct customer contact, enabling them to better understand their clients and respond to market shifts more quickly.

To understand how these hidden champions remain competitive, one must recognize their specialization in specific market categories. They excel at creating premium quality products in niche markets and possess a global reach. These companies invest heavily in Research and Development (R&D), and their culture of continuous innovation is fueled by both customers and top executives. All these elements contribute to their antifragility, allowing them to thrive and grow despite global market instability and unpredictability.

I noticed a distinct difference in mentality between Germany and Hong Kong. While most students in Hong Kong gravitate towards careers in the finance and banking industries, Germany offers a broader range of sectors like steel, iron, machinery, chemicals, locomotives, automobiles, and electronics. Rather than viewing university education as the only career path, Germany provides more vocational training for technical skills. The diverse job opportunities and emphasis on manufacturing and technological innovation make these countries less susceptible to risks.

Germany's economy is stable, characterized by low inflation, steady growth, a trade surplus, and a robust labor force. Effective state management helps in avoiding the recurrence of economic crises like the Great Depression and hyperinflation that contributed to the rise of Nazism and political instability in World War II. Understanding history is crucial to comprehending our origins, current challenges, and improving risk management in chaotic situations.

One of the main reasons I pursued an MBA was to refine my management skills in the global market. I was intrigued by the significant disparities in wealth between countries. For instance, after my study trip, I visited Switzerland and found myself eating the most expensive McDonald's Big Mac meal I've ever had, costing 12 Swiss Francs (approximately $93 in Hong Kong dollars). In contrast, a similar meal costs 7 Euros in Germany or roughly $62 in Hong Kong. The world can seem unjust if you're born in an economically weaker Eurozone country, such as rural Romania, where human trafficking is a severe issue. This journey allowed me to witness the elements of Germany's success and its antifragility throughout my visits to Berlin, Hamburg, Munich, and Frankfurt.

The lessons learned will serve me well as I aim to create an antifragile workplace at the management level. In today's rapidly changing digital environment, it's essential to build a company capable of thriving in unpredictability and uncertainty, beyond mere resilience or robustness. As I've observed in Germany, smaller, flat teams are antifragile, while large hierarchical structures are unstable. Antifragile organizations embrace a culture of experimentation and shun the "too-big-to-fail" mentality. In such settings, managers are wary of centralized power, and leaders trust their teams to handle complex challenges through decentralized decision-making.

Living in the age of artificial intelligence and automation is exhilarating. Our industry is undergoing a profound transformation, with an expanding horizon of untapped opportunities, increasingly connected devices, and more available real-world data. After completing my MBA, I continue to strive for greater antifragility in this fast-changing world, fortified by the unique perspectives gained from my international experiences in Germany.

My MBA Study Trip to Germany

Welcome back to another episode of Continuous Improvement, the podcast where we explore strategies and insights for personal and professional growth. I'm your host, Victor, and today we're diving into the fascinating world of antifragility, inspired by a recent study trip to Germany. So grab your favorite beverage, sit back, and let's embark on this journey together.

As many of you know, traveling can be an unpredictable adventure. But sometimes, within the chaos, we stumble upon valuable lessons that reshape our perspectives. And that's exactly what happened during my trip to Germany. Despite the flight delays and jet lag-induced presentations, the knowledge and experiences gained during the tour were truly transformative.

Germany, often regarded as a powerhouse in the world economy, holds a secret that sets it apart from many other nations: antifragility. During my travels, I discovered that Germany boasts the highest number of hidden champions—companies that thrive in niche markets, generate substantial revenue, and yet remain relatively unknown to the public.

These hidden champions, mainly small-to-medium enterprises, specialize in deep technology and are spread across the country. Unlike the traditional hierarchical structures of large corporations, these SMEs employ lean structures that foster a high-performance culture, increased employee engagement, and a people-oriented approach.

What truly intrigued me was how this decentralization and focus on specialized markets made these companies resilient to the uncertainties of the global economy. Their ability to adapt and innovate in response to market shifts is a testament to their antifragility.

Another key aspect of Germany's antifragility lies in its vibrant start-up scene. While large corporations may seemingly have more resources and influence, it is the nimble nature of startups and SMEs that allows them to navigate the ever-changing landscape more effectively. Germany's emphasis on vocational training and manufacturing further strengthens their resilience to economic risks.

What I found most striking was the contrast between the mentality I observed in Germany and the one prevalent in Hong Kong, where I reside. While many students in Hong Kong tend to gravitate towards careers in finance and banking, Germany offers a broader spectrum of sectors, including steel, iron, machinery, chemicals, locomotives, automobiles, and electronics.

This diversified approach to job opportunities, along with a strong emphasis on manufacturing and technological innovation, makes Germany less susceptible to risks associated with an over-reliance on a single industry. It's a reminder that a diversified economy can contribute to long-term stability.

The stability of Germany's economy can be attributed to effective state management, low inflation, steady growth, and a robust labor force. A deep understanding of history and the lessons learned from past economic crises have enabled Germany to build a solid foundation for success.

Armed with these insights from my study trip, I'm more determined than ever to bring the principles of antifragility to my own workplace. In a rapidly changing digital environment, it's crucial to foster a culture of experimentation and decentralize decision-making. We must move beyond the notion of resilience or robustness and strive for antifragility, where our organizations not only survive but thrive in unpredictability and uncertainty.

So as we navigate the age of artificial intelligence and automation, remember that the world is evolving at an exhilarating pace. Embrace the opportunities that arise, learn from diverse perspectives, and continuously seek to improve yourself and your organization.

That wraps up today's episode of Continuous Improvement. I hope you've gained valuable insights from our exploration of antifragility inspired by my trip to Germany. If you have any questions or want to share your own experiences, feel free to reach out to me on social media. And remember, growth and improvement are journeys that never truly end. Until next time, stay curious and keep striving for continuous improvement. This is Victor, signing off.

我的MBA德國學習之旅

旅行總是充滿了不確定性和偶然性。儘管我的航班在芬蘭赫爾辛基延誤,加上時差引起的壓力讓我在演講中感到壓力,但是此次旅程旅行最終還是讓我得到寶貴的經驗,讓我的專業管理技能得到了課堂以外的提升。

這次的旅程充滿了各種引人深思並且具有教育意義的講座,涵蓋了德國的宏觀經濟、歐洲聯盟、隱形冠軍、工業4.0、以及人工智能等各種主題。我們參觀了深度科技公司Wattx以及生產BMW汽車的Daimler AG工廠,開闊了視野。這次旅程中最重要的個人體會就是,德國具有反脆弱性。儘管德國在二戰期間脆弱不堪,但是它現在的財富狀況證明了它的反脆弱性。

這次旅程讓我明白,德國擁有最多的隱形冠軍公司——這些公司要么在全球排名前三,要么在歐洲排名第一,年收入超過500萬歐元,並且公眾認知度相對較低。許多中小企業專注於深度科技,德國經濟靠的是出口和創新。這些家族企業分布在德國各地,而不是只集中在柏林,在這1,307家隱形冠軍中。

從我的角度來看,由於其充滿活力的初創企業和分權化的特點,德國具有反脆弱性。大企業可能有強勢的等級結構和眾多的規定,但由於更高的人員流動率以及比較低的適應性和靈活性,它們更容易受到傷害。相比之下,中小企業擁有簡單的結構,這樣不僅能夠激發高效的工作文化,提高員工的參與度,還能更加以人為本。這種反脆弱性也體現在員工在公司內部各個職能間更加頻繁的轉換職位。中小企業的員工通常更能直接接觸客戶,這使他們能更好地理解客戶並更快地應對市場變化。

為了理解這些隱形冠軍如何保持競爭力,我們必須認識到它們在特定市場類別中的專業化。他們非常擅長在利基市場創造優質的產品,並且具有全球影響力。這些公司投入重金進行研發,他們持續創新的文化同時由客戶和最高管理層推動。所有這些元素共同為它們的反脆弱性做出了貢獻,使它們能夠在全球市場的不穩定和未知中生存並發展。

我注意到德國和香港的心態有明顯的區別。在香港,大多數學生都傾向於在金融和銀行業找工作,而德國提供更多的行業選擇,比如鋼鐵、鐵礦、機械、化學品、火車、汽車和電子產品等。德國不再將大學教育視為唯一的職業道路,而是為技術技能提供更多的職業培訓。這個多樣化的就業機會和對製造業和科技創新的重視使得這些國家更少受到風險的影響。

德國的經濟非常穩定,特點是低通脹、經濟穩步增長、貿易順差和強大的勞動力。有效的國家管理有助於避免經濟危機的重演,例如大蕭條和在二戰中導致納粹主義興起和政治不穩定的超通脹。理解歷史對於理解我們的起源、現在的挑戰以及在混亂局勢中改善風險管理至關重要。

我攻讀MBA的主要原因之一就是要在全球市場上提高自己的管理技能。我對不同國家之間的財富差異感到好奇。例如,我的學習之旅結束後,我去了瑞士,發現自己吃了迄今為止最貴的麥當勞大麥克套餐,花了12瑞士法郎(大約相當於93港元)。相比之下,在德國,同樣的餐點只需要7歐元,或者在香港約62元。如果你出生在經濟較弱的歐元區國家,例如羅馬尼亞的農村地區,那麼世界可能會讓你感到不公。這次旅程讓我看到了德國成功和反脆弱性的元素,無論是在我參觀柏林、漢堡、慕尼黑還是法蘭克福期間。

我學到的這些經驗將在我致力於在管理層創造反脆弱性工作環境的任務中起到重要的作用。在當今快速變化的數字環境中,建立一個能夠在不可預知性和不確定性中茁壯的公司比僅僅具有恢復力或堅韌性更為重要。如我在德國所觀察到的,規模較小、組織結構平坦的團隊能達到反脆弱性,而大型的層次結構則處於不穩定狀態。反脆弱性的組織擁抱實驗文化,並且避免"太大而不能倒"的心態。在這種環境下,管理者謹慎對待權力集中,領導者們對他們的團隊有信心,可以通過分權化的決策處理複雜的挑戰。

生活在人工智能和自動化的時代是令人充滿洋溢興奮。我們的行業正經歷著深刻的變革,面臨著擴大的未開發機會、越來越多的連接裝置以及更多的實際數據。在完成我的MBA學習後,我繼續努力以期在這個變化迅速的世界中獲得更大的反脆弱性,並且透過我在德國的國際經驗獲得獨特的視角。