node.js 如何使用 Mongoose 删除数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10081452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to drop a database with Mongoose?
提问by Yaron Naveh
I'm preparing a database creation script in Node.js and Mongoose. How can I check if the database already exists, and if so, drop (delete) it using Mongoose?
我正在用 Node.js 和 Mongoose 准备一个数据库创建脚本。如何检查数据库是否已经存在,如果存在,使用 Mongoose 删除(删除)它?
I could not find a way to drop it with Mongoose.
我找不到用猫鼬放下它的方法。
回答by drinchev
There is no method for dropping a collection from mongoose, the best you can do is remove the content of one :
没有从猫鼬中删除集合的方法,你能做的最好的事情就是删除一个的内容:
Model.remove({}, function(err) {
console.log('collection removed')
});
But there is a way to access the mongodb native javascript driver, which can be used for this
但是有一种方法可以访问mongodb本机javascript驱动程序,可以用于此
mongoose.connection.collections['collectionName'].drop( function(err) {
console.log('collection dropped');
});
Warning
警告
Make a backup before trying this in case anything goes wrong!
在尝试此操作之前进行备份,以防出现任何问题!
回答by hellslam
Mongoose will create a database if one does not already exist on connection, so once you make the connection, you can just query it to see if there is anything in it.
如果连接上不存在数据库,Mongoose 将创建一个数据库,因此一旦建立连接,您就可以查询它以查看其中是否有任何内容。
You can drop any database you are connected to:
您可以删除连接到的任何数据库:
var mongoose = require('mongoose');
/* Connect to the DB */
mongoose.connect('mongodb://localhost/mydatabase',function(){
/* Drop the DB */
mongoose.connection.db.dropDatabase();
});
回答by silverfighter
If you modify @hellslam's solution like this then it will work
如果您像这样修改@hellslam 的解决方案,那么它将起作用
I use this technique to drop the Database after my integration tests
我使用这种技术在集成测试后删除数据库
//CoffeeScript
mongoose = require "mongoose"
conn = mongoose.connect("mongodb://localhost/mydb")
conn.connection.db.dropDatabase()
//JavaScript
var conn, mongoose;
mongoose = require("mongoose");
conn = mongoose.connect("mongodb://localhost/mydb");
conn.connection.db.dropDatabase();
HTH at least it did for me, so I decided to share =)
HTH 至少对我有用,所以我决定分享 =)
回答by zafrani
Tried @hellslam's and @silverfighter's answers. I found a race condition holding my tests back. In my case I'm running mocha tests and in the before function of the test I want to erase the entire DB. Here's what works for me.
尝试了@hellslam 和@silverfighter 的答案。我发现一个竞争条件阻碍了我的测试。就我而言,我正在运行 mocha 测试,并且在测试的 before 函数中,我想擦除整个数据库。这对我有用。
var con = mongoose.connect('mongodb://localhost/mydatabase');
mongoose.connection.on('open', function(){
con.connection.db.dropDatabase(function(err, result){
done();
});
});
You can read more https://github.com/Automattic/mongoose/issues/1469
回答by Andre M
An updated answer, for 4.6.0+, if you have a preference for promises (see docs):
更新的答案,适用于 4.6.0+,如果您偏爱承诺(请参阅文档):
mongoose.connect('mongodb://localhost/mydb', { useMongoClient: true })
.then((connection) => {
connection.db.dropDatabase();
// alternatively:
// mongoose.connection.db.dropDatabase();
});
I tested this code in my own code, using mongoose 4.13.6. Also, note the use of the useMongoClientoption (see docs). Docs indicate:
我在自己的代码中测试了这段代码,使用的是 mongoose 4.13.6。另外,请注意该useMongoClient选项的使用(请参阅文档)。文档指出:
Mongoose's default connection logic is deprecated as of 4.11.0. Please opt in to the new connection logic using the useMongoClient option, but make sure you test your connections first if you're upgrading an existing codebase!
Mongoose 的默认连接逻辑自 4.11.0 起已弃用。请使用 useMongoClient 选项选择新的连接逻辑,但如果您要升级现有代码库,请确保首先测试您的连接!
回答by Eric Caron
The difficulty I've had with the other solutions is they rely on restarting your application if you want to get the indexes working again.
我在其他解决方案中遇到的困难是,如果您想让索引再次工作,它们依赖于重新启动您的应用程序。
For my needs (i.e. being able to run a unit test the nukes all collections, then recreates them along with their indexes), I ended up implementing this solution:
为了我的需要(即能够对所有集合进行单元测试,然后重新创建它们及其索引),我最终实现了这个解决方案:
This relies on the underscore.jsand async.jslibraries to assemble the indexes in parellel, it could be unwound if you're against that library but I leave that as an exerciser for the developer.
这依赖于underscore.js和async.js库以并行方式组装索引,如果您反对该库,它可能会被解除,但我将其留给开发人员作为练习者。
mongoose.connection.db.executeDbCommand( {dropDatabase:1}, function(err, result) {
var mongoPath = mongoose.connections[0].host + ':' + mongoose.connections[0].port + '/' + mongoose.connections[0].name
//Kill the current connection, then re-establish it
mongoose.connection.close()
mongoose.connect('mongodb://' + mongoPath, function(err){
var asyncFunctions = []
//Loop through all the known schemas, and execute an ensureIndex to make sure we're clean
_.each(mongoose.connections[0].base.modelSchemas, function(schema, key) {
asyncFunctions.push(function(cb){
mongoose.model(key, schema).ensureIndexes(function(){
return cb()
})
})
})
async.parallel(asyncFunctions, function(err) {
console.log('Done dumping all collections and recreating indexes')
})
})
})
回答by Danish
To empty a particular collection in a database:
要清空数据库中的特定集合:
model.remove(function(err, p){
if(err){
throw err;
} else{
console.log('No Of Documents deleted:' + p);
}
});
Note:
笔记:
- Choose a model referring to particular schema(schema of collection you wish to delete).
- This operation will not delete collection name from database.
- This deletes all the documents in a collection.
- 选择一个引用特定模式的模型(您希望删除的集合模式)。
- 此操作不会从数据库中删除集合名称。
- 这将删除集合中的所有文档。
回答by user3344977
This works for me as of Mongoose v4.7.0:
从 Mongoose 开始,这对我有用v4.7.0:
mongoose.connection.dropDatabase();
回答by Mark Stosberg
The best way to drop your database in Mongoose depends on which version of Mongoose you are using. If you are using a version of Mongoose that 4.6.4 or newer, then this method added in that release is likely going to work fine for you:
在 Mongoose 中删除数据库的最佳方法取决于您使用的 Mongoose 版本。如果您使用的是 4.6.4 或更高版本的 Mongoose,那么该版本中添加的此方法可能适合您:
mongoose.connection.dropDatabase();
In older releases this method did not exist. Instead, you were to use a direct MongoDB call:
在旧版本中,此方法不存在。相反,您将使用直接的 MongoDB 调用:
mongoose.connection.db.dropDatabase();
However, if this was run just after the database connection was created, it could possibly fail silently. This is related to the connection actually be asynchronous and not being set up yet when the command happens. This is not normally a problem for other Mongoose calls like .find(), which queue until the connection is open and then run.
但是,如果这只是在创建数据库连接之后运行,它可能会以静默方式失败。这与连接实际上是异步的并且在命令发生时尚未建立有关。对于其他 Mongoose 调用(例如 ).find(),这通常不是问题,它会排队直到连接打开然后运行。
If you look at the source code for the dropDatabase()shortcut that was added, you can see it was designed to solve this exact problem. It checks to see if the connection is open and ready. If so, it fires the command immediately. If not, it registers the command to run when the database connection has opened.
如果您查看dropDatabase()添加的快捷方式的源代码,您会发现它旨在解决这个确切的问题。它会检查连接是否打开并准备就绪。如果是这样,它会立即触发命令。如果没有,它会注册在数据库连接打开时运行的命令。
Some of the suggestions above recommend alwaysputting your dropDatabasecommand in the openhandler. But that only works in the case when the connection is not open yet.
上面的一些建议建议始终将您的dropDatabase命令放在open处理程序中。但这仅适用于连接尚未打开的情况。
Connection.prototype.dropDatabase = function(callback) {
var Promise = PromiseProvider.get();
var _this = this;
var promise = new Promise.ES6(function(resolve, reject) {
if (_this.readyState !== STATES.connected) {
_this.on('open', function() {
_this.db.dropDatabase(function(error) {
if (error) {
reject(error);
} else {
resolve();
}
});
});
} else {
_this.db.dropDatabase(function(error) {
if (error) {
reject(error);
} else {
resolve();
}
});
}
});
if (callback) {
promise.then(function() { callback(); }, callback);
}
return promise;
};
Here's a simple version of the above logic that can be used with earlier Mongoose versions:
这是上述逻辑的一个简单版本,可用于早期 Mongoose 版本:
// This shim is backported from Mongoose 4.6.4 to reliably drop a database
// http://stackoverflow.com/a/42860208/254318
// The first arg should be "mongoose.connection"
function dropDatabase (connection, callback) {
// readyState 1 === 'connected'
if (connection.readyState !== 1) {
connection.on('open', function() {
connection.db.dropDatabase(callback);
});
} else {
connection.db.dropDatabase(callback);
}
}
回答by Rayjax
Mongoose 4.6.0+:
猫鼬 4.6.0+:
mongoose.connect('mongodb://localhost/mydb')
mongoose.connection.once('connected', () => {
mongoose.connection.db.dropDatabase();
});
Passing a callback to connect won't work anymore:
将回调传递给连接将不再起作用:
TypeError: Cannot read property 'commandsTakeWriteConcern' of null
类型错误:无法读取 null 的属性“commandsTakeWriteConcern”

