Yar*_*veh 95 mongoose mongodb node.js
我正在Node.js和Mongoose中准备一个数据库创建脚本.如何检查数据库是否已存在,如果是,请使用Mongoose删除(删除)它?
我找不到用Mongoose放弃它的方法.
dri*_*hev 164
没有从mongoose中删除集合的方法,你可以做的最好是删除一个集合的内容:
Model.remove({}, function(err) {
console.log('collection removed')
});
Run Code Online (Sandbox Code Playgroud)
但有一种方法可以访问mongodb本机javascript驱动程序,可用于此
mongoose.connection.collections['collectionName'].drop( function(err) {
console.log('collection dropped');
});
Run Code Online (Sandbox Code Playgroud)
在尝试此操作之前进行备份,以防出现任何问题!
小智 75
Mongoose将创建一个数据库(如果连接上尚不存在),因此一旦建立连接,您只需查询它以查看其中是否有任何内容.
您可以删除所有连接的数据库:
var mongoose = require('mongoose');
/* Connect to the DB */
mongoose.connect('mongodb://localhost/mydatabase',function(){
/* Drop the DB */
mongoose.connection.db.dropDatabase();
});
Run Code Online (Sandbox Code Playgroud)
sil*_*ter 14
如果您像这样修改@hellslam的解决方案,那么它将起作用
我使用这种技术在集成测试后删除数据库
//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();
Run Code Online (Sandbox Code Playgroud)
HTH至少它对我有用,所以我决定分享=)
试过@hellslam和@ silverfighter的答案.我发现一个竞争条件让我的测试恢复了.在我的情况下,我正在运行mocha测试,在测试的before函数中,我想擦除整个DB.这对我有用.
var con = mongoose.connect('mongodb://localhost/mydatabase');
mongoose.connection.on('open', function(){
con.connection.db.dropDatabase(function(err, result){
done();
});
});
Run Code Online (Sandbox Code Playgroud)
您可以阅读更多https://github.com/Automattic/mongoose/issues/1469
小智 6
2020年更新
创建一个新文件,将其命名为 drop.js 并放入其中
require('dotenv').config()
const url = process.env.ATLAS_URI;
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
});
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
mongoose.connection.dropDatabase().then(
async() => {
try {
mongoose.connection.close()
}
catch (err) {
console.log(err)
}
}
);
Run Code Online (Sandbox Code Playgroud)
在你的 package.json 中
in your package.json
"scripts": {
"drop": "node models/drop.js",
}
Run Code Online (Sandbox Code Playgroud)
在你的控制台上运行它并
我对其他解决方案的困难在于,如果您想让索引再次运行,他们依赖于重新启动您的应用程序.
根据我的需求(即能够运行单元测试核武器所有集合,然后重新创建它们及其索引),我最终实现了这个解决方案:
这依赖于underscore.js和async.js库来组装parellel中的索引,如果你反对那个库,它可以解开,但我把它作为开发人员的练习器.
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')
})
})
})
Run Code Online (Sandbox Code Playgroud)
从 Mongoose 开始,这对我有用v4.7.0:
mongoose.connection.dropDatabase();
Run Code Online (Sandbox Code Playgroud)
如果您对诺言有偏爱,请为4.6.0+更新答案(请参阅docs):
mongoose.connect('mongodb://localhost/mydb', { useMongoClient: true })
.then((connection) => {
connection.db.dropDatabase();
// alternatively:
// mongoose.connection.db.dropDatabase();
});
Run Code Online (Sandbox Code Playgroud)
我使用猫鼬4.13.6在自己的代码中测试了此代码。另外,请注意该useMongoClient选项的使用(请参阅docs)。文件显示:
从4.11.0开始,Mongoose的默认连接逻辑已弃用。请使用useMongoClient选项选择加入新的连接逻辑,但是如果要升级现有代码库,请确保先测试连接!
| 归档时间: |
|
| 查看次数: |
92659 次 |
| 最近记录: |