我正在使用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模型时。
出现错误的实现代码如下:
``` (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 }
那么我在这里做错了什么?谢谢!