2019-05-06 11:31:26 +00:00
|
|
|
|
---
|
|
|
|
|
id: 587d7fb7367417b2b2512c0d
|
2021-02-16 21:01:20 +00:00
|
|
|
|
title: 使用 model.findById() 方法,根据 _id 来搜索数据
|
2019-05-06 11:31:26 +00:00
|
|
|
|
challengeType: 2
|
2020-09-17 10:53:54 +00:00
|
|
|
|
forumTopicId: 301544
|
2021-01-13 02:31:00 +00:00
|
|
|
|
dashedName: use-model-findbyid-to-search-your-database-by-id
|
2019-05-06 11:31:26 +00:00
|
|
|
|
---
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --description--
|
2019-05-06 11:31:26 +00:00
|
|
|
|
|
2021-02-16 21:01:20 +00:00
|
|
|
|
在保存 document 的时候,MongoDB 会自动为它添加 `_id` 字段,并给该字段设置一个唯一的仅包含数字和字母的值。 通过 `_id` 搜索是一个十分常见的操作,为此,Mongoose 提供了一个专门的方法。
|
2019-05-06 11:31:26 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --instructions--
|
2019-05-06 11:31:26 +00:00
|
|
|
|
|
2021-02-16 21:01:20 +00:00
|
|
|
|
修改 `findPersonById`,用 `Model.findById() -> Person` 来查询唯一一个给定 `_id` 的人, 把函数参数 `personId` 作为查询键。
|
2019-05-06 11:31:26 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --hints--
|
2019-05-06 11:31:26 +00:00
|
|
|
|
|
2021-02-16 21:01:20 +00:00
|
|
|
|
应成功地根据 Id 找到对应的数据
|
2019-05-06 11:31:26 +00:00
|
|
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
|
(getUserInput) =>
|
|
|
|
|
$.get(getUserInput('url') + '/_api/find-by-id').then(
|
|
|
|
|
(data) => {
|
|
|
|
|
assert.equal(data.name, 'test', 'item.name is not what expected');
|
|
|
|
|
assert.equal(data.age, 0, 'item.age is not what expected');
|
|
|
|
|
assert.deepEqual(
|
|
|
|
|
data.favoriteFoods,
|
|
|
|
|
['none'],
|
|
|
|
|
'item.favoriteFoods is not what expected'
|
|
|
|
|
);
|
|
|
|
|
assert.equal(data.__v, 0, 'The item should be not previously edited');
|
|
|
|
|
},
|
|
|
|
|
(xhr) => {
|
|
|
|
|
throw new Error(xhr.responseText);
|
|
|
|
|
}
|
|
|
|
|
);
|
2019-05-06 11:31:26 +00:00
|
|
|
|
```
|
2020-08-13 15:24:35 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --solutions--
|
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
```js
|
|
|
|
|
/**
|
|
|
|
|
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.
|
|
|
|
|
*/
|
|
|
|
|
```
|