【问题标题】:DeprecationWarning: `ensureIndex()` is deprecated in Mongoose >= 4.12.0, use `createIndex()` instead弃用警告:`ensureIndex()` 在 Mongoose >= 4.12.0 中已弃用,请改用`createIndex()`
【发布时间】:2020-03-27 21:23:47
【问题描述】:

您好,我创建了节点应用程序,它运行良好,但从最近 2 天开始出现此错误 我尝试升级猫鼬,但仍然出现同样的错误

DeprecationWarning:ensureIndex() 在 Mongoose >= 4.12.0 中已弃用,请改用 createIndex()

因此,我的应用程序已停止工作

这里是我连接 mongodb 的代码

mongoose.connect(config.mongo.uri, {useMongoClient: true});
  mongoose.connection.on('error', function (err) {
  console.error(`MongoDB connection error: ${err}`);
  process.exit(-1); // eslint-disable-line no-process-exit 
 });

有没有人能解决这个问题 提前谢谢。

【问题讨论】:

  • 你的 ensureIndex() 代码是什么样的?
  • 弃用警告不能成为您的应用停止工作的原因。更有可能使用useMongoClient
  • 我没有为 ensureIndex() 编写代码,我不知道为什么我的应用程序在收到此警告后无法运行
  • @kalpeshR 删除 useMongoClient : true 看看它是否再次起作用。
  • 我也有这个问题。猫鼬一直在搞乱变化。我在使用 gridfs 流时遇到问题

标签: mongodb mongoose


【解决方案1】:

我终于通过official mongoose docs 简单地解决了这个问题。

基本上有一个标志可以通过连接选项如下:

mongoose.connect(dbconfig.database, {
    useCreateIndex: true
});

这删除了弃用警告消息,而无需进一步修改我的代码。

【讨论】:

    【解决方案2】:

    MongoStore 导致此通知。请升级 connect-mongo

    https://github.com/Automattic/mongoose/issues/5692

    npm i connect-mongo@2.0.0 --save
    

    【讨论】:

      【解决方案3】:

      您可以在连接上添加此代码块:

      mongoose.set("useCreateIndex", true);
      

      这将解决您的问题。我是这样使用的:

      import mongoose from "mongoose";
      mongoose.connect(`mongodb://localhost:27017/shopping`, {
          useUnifiedTopology: true,
          useNewUrlParser: true
        })
        .then(() => {
          console.log("connection to mongodb successful ...");
        })
        .catch(error =>
          console.log(`there is something wrong on mongoDB connection : ${error}`)
        );
      
      mongoose.set("useCreateIndex", true);
      

      【讨论】:

        【解决方案4】:

        我已将 mongoose 版本升级到 4.9.9,现在我没有收到任何警告

        【讨论】:

          【解决方案5】:

          遵循 Mongodb 文档。您必须禁用 autoIndex: false,然后调用 User createIndexes 函数。您需要像这样配置您的架构。

          
          account_type: {
                  type: Number,
                  default: config.accountType.admin
              },
              account_status: {
                  type: Number,
                  default: config.accountStatus.unVerified
              },
              socket_id: String,
              picture_url: {
                  type: String
              }
          },{
              timestamps: true,
              autoIndex: false
          });
          
          const User = mongoose.model('User', userSchema);
          
          User.createIndexes();
          
          // export model
          module.exports = User;
          
          
          

          【讨论】:

            猜你喜欢
            • 2021-12-19
            • 1970-01-01
            • 2019-01-25
            • 2023-04-07
            • 2019-03-05
            • 1970-01-01
            • 1970-01-01
            • 2020-12-06
            • 2015-03-23
            相关资源
            最近更新 更多