2019-05-06 07:31:26 -04:00
|
|
|
|
---
|
|
|
|
|
id: 587d7fb6367417b2b2512c06
|
2020-12-16 00:37:30 -07:00
|
|
|
|
title: 安装和设置 Mongoose
|
2019-05-06 07:31:26 -04:00
|
|
|
|
challengeType: 2
|
2020-09-17 03:53:54 -07:00
|
|
|
|
forumTopicId: 301540
|
2019-05-06 07:31:26 -04:00
|
|
|
|
---
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --description--
|
|
|
|
|
|
|
|
|
|
在 package.json 文件中添加 mongodb 和 mongoose 作为项目依赖,然后引入 Mongoose。之后,将 MongoDB Atlas 的 URI 作为 MONGO_URI 字段存储在私有的 `.env` 文件中。然后使用单引号或双引号包裹 URI,最后通过以下的代码片段来连接数据库:
|
2020-09-17 03:53:54 -07:00
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
mongoose.connect(<Your URI>, { useNewUrlParser: true, useUnifiedTopology: true });
|
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --hints--
|
2019-05-06 07:31:26 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
"mongodb" 应在 package.json 中作为依赖项定义
|
2019-05-06 07:31:26 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
```js
|
|
|
|
|
(getUserInput) =>
|
|
|
|
|
$.get(getUserInput('url') + '/_api/file/package.json').then(
|
|
|
|
|
(data) => {
|
|
|
|
|
var packJson = JSON.parse(data);
|
|
|
|
|
assert.property(packJson.dependencies, 'mongodb');
|
|
|
|
|
},
|
|
|
|
|
(xhr) => {
|
|
|
|
|
throw new Error(xhr.responseText);
|
|
|
|
|
}
|
|
|
|
|
);
|
2019-05-06 07:31:26 -04:00
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
"mongoose" 应在 package.json 中作为依赖项定义
|
2019-05-06 07:31:26 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
```js
|
|
|
|
|
(getUserInput) =>
|
|
|
|
|
$.get(getUserInput('url') + '/_api/file/package.json').then(
|
|
|
|
|
(data) => {
|
|
|
|
|
var packJson = JSON.parse(data);
|
|
|
|
|
assert.property(packJson.dependencies, 'mongoose');
|
|
|
|
|
},
|
|
|
|
|
(xhr) => {
|
|
|
|
|
throw new Error(xhr.responseText);
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
```
|
2019-05-06 07:31:26 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
应使用 "mongoose" 连接数据库
|
2019-05-06 07:31:26 -04:00
|
|
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
|
(getUserInput) =>
|
|
|
|
|
$.get(getUserInput('url') + '/_api/is-mongoose-ok').then(
|
|
|
|
|
(data) => {
|
|
|
|
|
assert.isTrue(data.isMongooseOk, 'mongoose is not connected');
|
|
|
|
|
},
|
|
|
|
|
(xhr) => {
|
|
|
|
|
throw new Error(xhr.responseText);
|
|
|
|
|
}
|
|
|
|
|
);
|
2019-05-06 07:31:26 -04:00
|
|
|
|
```
|
2020-08-13 17:24:35 +02:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --solutions--
|
|
|
|
|
|