使用 Mongoose 删除索引的推荐方法是什么? [英] What is the recommended way to drop indexes using Mongoose?

查看:38
本文介绍了使用 Mongoose 删除索引的推荐方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为 MongoDB 数据库创建多个部署脚本,例如数据迁移和固定装置,但我找不到有关如何使用 Mongoose API 删除索引的足够信息.这在使用官方 MongoDB API 时非常简单:

I need to create several deployment scripts like data migration and fixtures for a MongoDB database and I couldn't find enough information about how to drop indexes using Mongoose API. This is pretty straight-forward when using the official MongoDB API:

删除指定集合上的所有索引:

db.collection.dropIndexes();

To delete all indexes on the specified collection:

db.collection.dropIndexes();

但是,我想为此使用 Mongoose,并尝试使用改编自 这篇文章,但没有成功:

However, I would like to use Mongoose for this and I tried to use executeDbCommand adapted from this post, but with no success:

mongoose.connection.db.executeDbCommand({ dropIndexes: collectionName, index: '*' },
  function(err, result) { /* ... */ });

我应该使用 Node.js 的官方 MongoDB API 还是我在这种方法中遗漏了一些东西?

Should I use the official MongoDB API for Node.js or I just missed something in this approach?

推荐答案

要通过集合的 Mongoose 模型执行此操作,您可以调用 dropAllIndexes:

To do this via the Mongoose model for the collection, you can call dropAllIndexes of the native collection:

MyModel.collection.dropAllIndexes(function (err, results) {
    // Handle errors
});

更新

dropAllIndexes 在本机驱动程序的 2.x 版本中已弃用,因此 dropIndexes 应该被使用:

dropAllIndexes is deprecated in the 2.x version of the native driver, so dropIndexes should be used instead:

MyModel.collection.dropIndexes(function (err, results) {
    // Handle errors
});

这篇关于使用 Mongoose 删除索引的推荐方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆