我需要使用mongoose插入一些数据,但是用户在插入时会提供集合的名称,所以我首先要检查集合是否存在。
我知道如何检查集合是否存在的方式是查询system.namespaces
集合。我可以看到3种可行的方法。
system.namespaces
的方法(可能定义与数据库中的模式匹配的模式)。数字3
是最不优雅的,也是我想要避免的,我不想加载驱动程序的另一个实例,也不想在mongoose创建一个连接时创建新的连接。
写完这篇文章之后我会尝试编号1
。我刚检查system.namespaces
,架构看起来很简单
我仍然希望听到一些意见。
谢谢!
答案 0 :(得分:32)
选项2可能是最干净的。假设您使用Connection
打开了一个名为conn
的Mongoose mongoose.createConnection
对象,则可以通过Db
访问本机mongo conn.db
对象。从那里你可以打电话给collectionNames
,它应该提供你想要的东西:
conn.db.collectionNames(function (err, names) {
// names contains an array of objects that contain the collection names
});
您还可以将集合名称作为参数传递给collectionNames
,以便将结果过滤到您正在寻找的内容。
Mongoose 4.x更新
在Mongoose 4.x使用的2.x版本的MongoDB本机驱动程序中,collectionNames
已替换为listCollections
,它接受过滤器并返回游标,因此您可以这样做:
mongoose.connection.db.listCollections({name: 'mycollectionname'})
.next(function(err, collinfo) {
if (collinfo) {
// The collection exists
}
});
答案 1 :(得分:1)
这对我有用(猫鼬版本5.1.1):
const mongoose = require('mongoose');
const mongoURI = 'mongodb://localhost:27017/mydb'
// notice the mongoose.createConnection instead of mongoose.connect
const conn = mongoose.createConnection(mongoURI);
conn.on('open', function () {
conn.db.listCollections().toArray(function (err, collectionNames) {
if (err) {
console.log(err);
return;
}
console.log(collectionNames);
conn.close();
});
});
答案 2 :(得分:0)
这是另一个对我有用的选项(很少使用express
,但我认为没有它就可以了)。假设您导入了一个模型。并且,假设Blog
是模型的名称。
const app = express();
const Blog = require('./models/blog');
app.post('/example', (req, res) => {
Blog.findOne({name: 'collectionname'})
.then(result => {
if(result) {
//If it exists
}
})
})
'''
result
是null
或object
。
答案 3 :(得分:-8)
在集合列表中查找集合
public function CollectionExists($collectionName)
{
$mongo = new Mongo();
$collectionArr = $mongo->selectDB('yourrec')->listCollections();
if (in_array($collectionName, $collectionArr)) {
return true;
}
return false;
}