# 文档（documents）

> 原文：[Documents](http://mongoosejs.com/docs/documents.html)\
> 翻译：小虾米（QQ:509129）

## Documents

Mongoose[文档](http://mongoosejs.com/docs/api.html#document-js)代表了文档存储在MongoDB的一对一映射。每个文档都是它的[模型](http://mongoosejs.com/docs/models.html)的一个实例。

### 检索

有许多方法从MongoDB文档检索。我们不会涵盖在在这一部分中。查看查询详细信息的[‘querying’](http://mongoosejs.com/docs/queries.html)章节。

### 更新

有一些方法来更新文档。我们先看看使用`findById`的传统方法：

```javascript
Tank.findById(id, function (err, tank) {
  if (err) return handleError(err);

  tank.size = 'large';
  tank.save(function (err) {
    if (err) return handleError(err);
    res.send(tank);
  });
});
```

这种方法包括首先检索文档从Mongo，然后发出更新命令（通过触发调用保存）。然而，如果我们不需要的文档在我们的应用程序中返回，只需要更新一个属性直接在数据库、`Model#update`对我们是正确的：

```javascript
Tank.update({ _id: id }, { $set: { size: 'large' }}, callback);
```

如果我们的应用程序需要文档返回，则需要另一个方法，往往[更好](http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate)，选项：

```javascript
Tank.findByIdAndUpdate(id, { $set: { size: 'large' }}, function (err, tank) {
  if (err) return handleError(err);
  res.send(tank);
});
```

`findAndUpdate/Remove` 静态方法都在最多一个文档中进行更改，并返回它只有一个调用数据库。有几种不同的`findandmodify`主题。阅读[API文档](http://mongoosejs.com/docs/api.html)的更多细节。注意`findAndUpdate/Remove`不执行任何钩子或验证在在数据库中进行更改 之前。如果你需要钩子和验证,首先查询文档,然后保存它。

> 译者注：[findByIdAndRemove](http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove)，[findOneAndUpdate](http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate)，[findAndModify](https://docs.mongodb.com/manual/reference/command/findAndModify/)

### 验证

在保存文档之前，文档进行了验证。详情阅读[API文档](http://mongoosejs.com/docs/api.html#document_Document-validate)或[validation](http://mongoosejs.com/docs/validation.html)章节。

### 下一步

既然我们已经掌握了文档，让我们看看[子文档](http://mongoosejs.com/docs/subdocs.html)。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mongoose.shujuwajue.com/guide/documents.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
