为什么会出现createIndex弃用错误?

3
我正在使用TypeScript构建一个express服务器,并使用mongoose与MongoDB Atlas进行交互。最近,我决定在我的应用程序中使用多个数据库,并更改模式以适应这种新的“架构”。但是这样做会出现一个弃用警告:
``` (node: 2096) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead. (Use node --trace-deprecation ... to show where the warning was created) ```
我已经找出错误发生的位置。它发生在我将模式映射到mongoose模型时。
出现错误的实现代码如下:
const db = mongoose.connection.useDb("Authentication");
const User = db.model<UserInterface>("User", UserSchema);

未发生错误的实现代码:

const User = mongoose.model<UserInterface>("User", UserSchema);

以下是我连接 MongoDB 的逻辑:

import mongoose from "mongoose";

async function connect() {
   try {
      const uri = <string>process.env.MONGO_URI;
      await mongoose.connect(uri, {
         useNewUrlParser: true,
         useUnifiedTopology: true,
         useCreateIndex: true,
      });
      console.log("MongoDB Connected...");
      return;
   } catch (err) {
      process.exit(1);
   }
}

export default connect;

如您所见,我已经有了useCreateIndex: true,所以我不知道错误为什么会发生。当我将其添加到模式中时错误确实消失了,但我认为这不是一个好的解决方案:

{ timestamps: true, autoIndex: false }

那么我在这里做错了什么?谢谢!


1
@MattU 我撤回之前的话哈哈。似乎在执行mongoose.connect()之前使用mongoose.set(...)进行设置是解决方案。我在你链接的帖子评论中找到了它。谢谢! - camelCaseIsGoodPractice
这回答了你的问题吗?MongoDB mongoose 废弃警告 - PM 77-1
1个回答

1

好的,看起来解决方案是在使用mongoose.connect(...)之前使用mongoose.set(...)。这样做可以使我的弃用警告消失:

import mongoose from "mongoose";

async function connect() {
   try {
      const uri = <string>process.env.MONGO_URI;
      mongoose.set("useNewUrlParser", true);
      mongoose.set("useUnifiedTopology", true);
      mongoose.set("useCreateIndex", true);
      mongoose.set("useFindAndModify", false);
      await mongoose.connect(uri);
      console.log("MongoDB Connected...");
      return;
   } catch (err) {
      process.exit(1);
   }
}

export default connect;

我经常看到其他人在connect函数中设置这些选项,所以我不知道set函数的存在。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接