Reputation: 188
So I am using TypeScript to build an express
server using mongoose
to interact with MongoDB Atlas
. Recently I decided to use multiple databases inside my app and change up my schemas to accommodate this new "architecture". However doing so made a deprecation warning
appear:
(node:2096) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead. (Use
node --trace-deprecation ...
to show where the warning was created)
I have already pinpointed where the error is happening. It is happening when I map the schema to a mongoose model.
Implementation code where error does occur:
const db = mongoose.connection.useDb("Authentication");
const User = db.model<UserInterface>("User", UserSchema);
Implementation code where error does NOT occur:
const User = mongoose.model<UserInterface>("User", UserSchema);
Here is my connection logic to 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;
As you can see I already have useCreateIndex: true
so I don't know why the error is occuring. The error does go away when I add this to the schema but I don't think its a good solution:
{ timestamps: true, autoIndex: false }
So what am I doing wrong here? Thank You!
Upvotes: 3
Views: 1147
Reputation: 188
Ok so looks like the solution was to use mongoose.set(...)
before using mongoose.connect(...)
. So this made my deprecation warning disappear:
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;
I always saw others setting these options inside the connect function so I never knew about the set function.
Upvotes: 1