MongoDB
弃用警告
原文链接:https://mongoosejs.com/docs/deprecations.html#-findandmodify-
在MongoDB Node.js驱动程序中有几个弃用,Mongoose提供了解决这些弃用警告的选项
摘要
要修复所有弃用警告,请按照以下步骤操作:
mongoose.set('useNewUrlParser', true)
mongoose.set('useFindAndModify', false)
mongoose.set('useCreateIndex', true)
- 将
update()
替换为updateOne()
,updateMany()
,replaceOne()
- 将
remove()
替换为deleteOne()
或deleteMany()
- 将
count()
替换为countDocuments()
, 除非您想要计算整个集合中有多少文档(没有过滤器)。在后一种情况下,使用estimatedDocumentCount()
useNewUrlParser
选项
默认情况下,mongoose.connect()
会打印出以下警告:
DeprecationWarning: current URL string parser is deprecated, and will be
removed in a future version. To use the new parser, pass option
{ useNewUrlParser: true } to MongoClient.connect.
MongoDB Node.js驱动程序重写了用于解析MongoDB连接字符串的工具。因为这是一个很大的变化,所以他们将新的连接字符串解析器放在一个标志后面。要打开此选项,请将useNewUrlParser
选项传递给 mongoose.connect()
或mongoose.createConnection()
。
mongoose.connect(uri, {
useNewUrlParser: true })
mongoose.createConnection(uri, {
useNewUrlParser: true })
您还可以将全局选项设置useNewUrlParser
为默认情况下为每个连接打开。
mongoose.set('useNewUrlParser', true)
要测试您的应用{ useNewUrlParser: true }
,您只需要检查您的应用是否成功连接。一旦Mongoose成功连接,URL解析器就不再重要了。
usefindAndModify
选项
如果使用Model.findOneAndUpdate()
,默认情况下会看到以下弃用警告之一。
DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `useFindAndModify` option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#-findandmodify-
DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
Mongoose很findOneAndUpdate()
早就预定了MongoDB驱动程序的findOneAndUpdate()
功能,所以它使用了MongoDB驱动程序的findAndModify()
功能。您可以使用useFindAndModify
全局选项选择使用MongoDB驱动程序的功能。
// 要让 mongoose 使用 `findOneAndUpdate()`.注意选项设置为`true`
// 默认选项为 false.
mongoose.set('useFindAndModify'