从 3.x 迁移到 4.x
¥Migrating from 3.x to 4.x
从 Mongoose 3 迁移到 Mongoose 4 时,有几个 向后突破的变化 需要注意。
¥There are several backwards-breaking changes to be aware of when migrating from Mongoose 3 to Mongoose 4.
findOneAndUpdate()
新字段现在默认为 false
¥findOneAndUpdate()
new field is now false
by default
Mongoose 的 findOneAndUpdate()
、findOneAndRemove()
、findByIdAndUpdate()
和 findByIdAndRemove()
函数只是 MongoDB findAndModify
命令 的封装器。MongoDB 服务器和 MongoDB NodeJS 驱动程序都默认将 new
选项设置为 false,但 mongoose 3 覆盖了此默认值。为了与 MongoDB 服务器的文档更加一致,mongoose 默认会使用 false。也就是说,findOneAndUpdate({}, { $set: { test: 1 } }, callback);
将返回应用 $set
操作之前的文档。
¥Mongoose's findOneAndUpdate()
, findOneAndRemove()
,
findByIdAndUpdate()
, and findByIdAndRemove()
functions are just
wrappers around MongoDB's
findAndModify
command.
Both the MongoDB server and the MongoDB NodeJS driver set the new
option
to false by default, but mongoose 3 overwrote this default. In order to be
more consistent with the MongoDB server's documentation, mongoose will
use false by default. That is,
findOneAndUpdate({}, { $set: { test: 1 } }, callback);
will return the
document as it was before the $set
operation was applied.
要返回包含更新修改的文档,请使用 new: true
选项。
¥To return the document with modifications made on the update, use the new: true
option.
MyModel.findOneAndUpdate({}, { $set: { test: 1 } }, { new: true }, callback);
CastError 和 ValidationError 现在使用 kind
而不是 type
来报告错误类型
¥CastError and ValidationError now use kind
instead of type
to report error types
在 Mongoose 3 中,CastError 和 ValidationError 有一个 type
字段。例如,用户定义的验证错误将具有包含字符串 '用户自定义' 的 type
属性。在 Mongoose 4 中,由于 V8 JavaScript 引擎内部使用 Error.type 属性,该属性已重命名为 kind
。
¥In Mongoose 3, CastError and ValidationError had a type
field. For instance, user defined validation errors would have a type
property that contained the string 'user defined'. In Mongoose 4, this property has been renamed to kind
due to the V8 JavaScript engine using the Error.type property internally.
查询现在有 .then()
功能
¥Query now has a .then()
function
在 mongoose 3 中,你需要在查询链上调用 .exec()
来获取 promise,就像 MyModel.find().exec().then();
一样。Mongoose 4 查询是 promise,因此你可以改为执行 MyModel.find().then()
。如果你使用诸如 q 的 Q.ninvoke()
之类的函数或以其他方式从 Promise 返回 Mongoose 查询,请务必小心。
¥In mongoose 3, you needed to call .exec()
on a query chain to get a
promise back, like MyModel.find().exec().then();
. Mongoose 4 queries are
promises, so you can do MyModel.find().then()
instead. Be careful if
you're using functions like
q's Q.ninvoke()
or
otherwise returning a mongoose query from a promise.
更多信息
¥More Info
相关博客文章:
¥Related blog posts: