Documents文档
Mongoose documents represent a one-to-one mapping to documents as stored in MongoDB. Mongoose文档表示存储在MongoDB中的文档的一对一映射。Each document is an instance of its Model.每个文档都是其模型的一个实例。
Documents vs Models文档与模型的对比Retrieving检索Updating Using使用save()
save()
更新Updating Using Queries使用查询更新Validating验证Overwriting覆盖
Documents vs Models文档与模型的对比
Document and Model are distinct classes in Mongoose. Document
和Model
是Mongoose中不同的类。The Model class is a subclass of the Document class. Model类是Document类的一个子类。When you use the Model constructor, you create a new document.当您使用Model构造函数时,您将创建一个新文档。
const MyModel = mongoose.model('Test', new Schema({ name: String }));
const doc = new MyModel();
doc instanceof MyModel; // true
doc instanceof mongoose.Model; // true
doc instanceof mongoose.Document; // true
In Mongoose, a "document" generally means an instance of a model. 在Mongoose中,“文档”通常意味着模型的一个实例。You should not have to create an instance of the Document class without going through a model.您不应该在不经过模型的情况下创建Document类的实例。
Retrieving检索
When you load documents from MongoDB using model functions like findOne(), you get a Mongoose document back.当您使用findOne()
等模型函数从MongoDB加载文档时,您会得到一个Mongoose文档。
const doc = await MyModel.findOne();
doc instanceof MyModel; // true
doc instanceof mongoose.Model; // true
doc instanceof mongoose.Document; // true
Updating Using save()
使用save()
更新
save()
Mongoose documents track changes. Mongoose文档跟踪更改。You can modify a document using vanilla JavaScript assignments and Mongoose will convert it into MongoDB update operators.您可以使用普通的JavaScript赋值修改文档,Mongoose会将其转换为MongoDB更新运算符。
doc.name = 'foo';
// Mongoose sends an `updateOne({ _id: doc._id }, { $set: { name: 'foo' } })` to MongoDB.Mongoose向MongoDB发送了一个`updateOne({ _id: doc._id }, { $set: { name: 'foo' } })`
await doc.save();
The save()
method returns a promise. save()
方法返回一个promise。If 如果save()
succeeds, the promise resolves to the document that was saved.save()
成功,promise将解析为已保存的文档。
doc.save().then(savedDoc => {
savedDoc === doc; // true
});
If the document with the corresponding 如果找不到具有相应_id
is not found, Mongoose will report a DocumentNotFoundError
:_id
的文档,Mongoose将报告DocumentNotFoundError
:
const doc = await MyModel.findOne();
// Delete the document so Mongoose won't be able to save changes删除文档,使Mongoose无法保存更改
await MyModel.deleteOne({ _id: doc._id });
doc.name = 'foo';
await doc.save(); // Throws 抛出DocumentNotFoundError
Updating Using Queries使用查询更新
The save() function is generally the right way to update a document with Mongoose. save()
函数通常是用Mongoose更新文档的正确方法。With 使用save()
, you get full validation and middleware.save()
,您可以获得完整的验证和中间件。
For cases when 对于save()
isn't flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.save()
不够灵活的情况,Mongoose允许您使用强制转换、中间件和有限的验证来创建自己的MongoDB更新。
// Update all documents in the `mymodels` collection
await MyModel.updateMany({}, { $set: { name: 'foo' } });
Note that 请注意update()
, updateMany()
, findOneAndUpdate()
, etc. update()
、updateMany()
、findOneAndUpdate()
等。do not execute 不要执行save()
middleware. If you need save middleware and full validation, first query for the document and then save()
it.save()
中间件。如果您需要保存中间件和完整验证,请先查询文档,然后save()
它。
Validating验证
Documents are casted and validated before they are saved. 在保存文档之前,对文档进行铸造和验证。Mongoose first casts values to the specified type and then validates them. Mongoose首先将值强制转换为指定的类型,然后验证它们。Internally, Mongoose calls the document's 在内部,Mongoose在保存之前调用文档的validate()
method before saving.validate()
方法。
const schema = new Schema({ name: String, age: { type: Number, min: 0 } });
const Person = mongoose.model('Person', schema);
const p = new Person({ name: 'foo', age: 'bar' });
// Cast to Number failed for value "bar" at path "age"
await p.validate();
const p2 = new Person({ name: 'foo', age: -1 });
// Path `age` (-1) is less than minimum allowed value (0).
await p2.validate();
Mongoose also supports limited validation on updates using the Mongoose还支持使用runValidators
option. runValidators
选项对更新进行有限验证。Mongoose casts parameters to query functions like 默认情况下,Mongoose将参数强制转换为查询函数,如findOne()
, updateOne()
by default. findOne()
、updateOne()
。However, Mongoose does not run validation on query function parameters by default. You need to set 然而,Mongoose默认情况下不会对查询函数参数进行验证。您需要设置runValidators: true
for Mongoose to validate.runValidators: true
,以便Mongoose进行验证。
// Cast to number failed for value "bar" at path "age"
await Person.updateOne({}, { age: 'bar' });
// Path `age` (-1) is less than minimum allowed value (0).
await Person.updateOne({}, { age: -1 }, { runValidators: true });
Read the validation guide for more details.有关更多详细信息,请阅读验证指南。
Overwriting覆盖
There are 2 different ways to overwrite a document (replacing all keys in the document). 覆盖文档有两种不同的方法(替换文档中的所有键)。One way is to use the 一种方法是使用Document#overwrite()
function followed by save()
.Document#overwrite()
函数,然后使用save()
。
const doc = await Person.findOne({ _id });
// Sets `name` and unsets all other properties设置`name`并取消设置所有其他属性
doc.overwrite({ name: 'Jean-Luc Picard' });
await doc.save();
The other way is to use Model.replaceOne().另一种方法是使用Model.replaceOne()
。
// Sets `name` and unsets all other properties设置`name`并取消设置所有其他属性
await Person.replaceOne({ _id }, { name: 'Jean-Luc Picard' });
Next Up下一步
Now that we've covered Documents, let's take a look at Subdocuments.现在我们已经介绍了文档,让我们来看一下子文档。