freeCodeCamp/curriculum/challenges/chinese-traditional/05-back-end-development-and.../mongodb-and-mongoose/install-and-set-up-mongoose.md

3.0 KiB
Raw Blame History

id title challengeType forumTopicId dashedName
587d7fb6367417b2b2512c06 安裝和設置 Mongoose 2 301540 install-and-set-up-mongoose

--description--

你可以採用下面的任意一種編寫代碼的方式來完成這些挑戰:

完成本項目後,請將一個正常運行的 demo項目演示託管在可以公開訪問的平臺。 然後在 Solution Link 字段中提交它的 URL。

在這個挑戰中,你將建立一個 MongoDB Atlas 數據庫並導入連接到它所需的軟件包。

按照這篇教程在 MongoDB Atlas 創建一個託管數據庫。

--instructions--

mongoose@^5.11.15 已添加到你項目的 package.json 文件中。 首先,在 myApp.js 中請求 mongoose 爲 mongoose。 接下來,創建一個 .env 文件並向其中添加一個 MONGO_URI 變量。 變量的值爲你的 MongoDB Atlas 數據庫 URI。 應用單引號或雙引號包裹 URI。請記住環境變量 = 兩邊不能有空格。 例如,MONGO_URI='VALUE'

注意: 如果你使用的是 Replit則無法創建 .env 文件。 相反,使用內置的 SECRETS 選項卡來添加變量。 在使用 SECRETS 選項卡時,不要將值括在引號中。

完成後,使用以下語法連接到數據庫:

mongoose.connect(<Your URI>, { useNewUrlParser: true, useUnifiedTopology: true });

--hints--

“mongoose version ^5.11.15” 依賴項應該在 package.json

(getUserInput) =>
  $.get(getUserInput('url') + '/_api/file/package.json').then(
    (data) => {
      var packJson = JSON.parse(data);
      assert.property(packJson.dependencies, 'mongoose');
      assert.match(
        packJson.dependencies.mongoose,
        /^\^5\.11\.15/,
        'Wrong version of "mongoose". It should be ^5.11.15'
      );
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );

應使用 “mongoose” 連接數據庫。

(getUserInput) =>
  $.get(getUserInput('url') + '/_api/is-mongoose-ok').then(
    (data) => {
      assert.isTrue(data.isMongooseOk, 'mongoose is not connected');
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );

--solutions--

/**
  Backend challenges don't need solutions, 
  because they would need to be tested against a full working project. 
  Please check our contributing guidelines to learn more.
*/