Node.js - Mongoose - 检查集合是否存在 [英] Node.js - Mongoose - Check if a collection exists
问题描述
我需要使用 mongoose 插入一些数据,但是集合的名称是在插入时用户提供的,所以我首先要检查集合是否存在.
I need to insert some data using mongoose but the name of the collection is provided by the user at the moment of the insertion, so I first have to check if the collection exists.
我知道如何检查集合是否存在的方法是查询 system.namespaces
集合.我可以看到 3 种可能的方法来做到这一点.
The way I know how to check if a collection exists is by querying the system.namespaces
collection. I can see 3 possible approaches to doing that.
- 找到一种使用 mongoose 查询
system.namespaces
的方法(可能定义一个与数据库中的模式匹配的模式). - 从 mongoose 获取一些底层 node-mongodb-native 对象并手动执行查询.无论如何,这是我想学习如何做的事情.
- 使用 node-mongodb-native(或其他一些驱动程序)的单独实例来执行查询
- Find a way to query
system.namespaces
using mongoose (maybe defining a schema that matches the one in the db). - Getting some underlying node-mongodb-native object from mongoose and performing the query manually. In any case, this is something I would like to learn how to do.
- Using a separate instance of a node-mongodb-native (or some other driver) to perform the query
数字 3
是最不优雅的,也是我试图避免的,我不想加载驱动程序的另一个实例,也不想在猫鼬已经创建一个连接时创建新连接.
Number 3
is the least elegant and the one i'm trying to avoid, I don't want to load another instance of the driver nor create a new connection when mongoose already created one.
我将在写完这篇文章后尝试编号 1
.我刚刚检查了 system.namespaces
并且架构看起来很简单
I'm going to try number 1
after writing this. I just checked system.namespaces
and the schema looks quite simple
我还是想听听大家的意见.
I'd still like to hear some opinions.
谢谢!
推荐答案
选项 2 可能是最干净的.假设您有一个名为 conn
的 Mongoose Connection
对象已使用 mongoose.createConnection
打开,您可以访问本机 mongo Db
对象通过 conn.db
.从那里你可以调用 collectionNames
应该提供您要查找的内容:
Option 2 is probably the cleanest. Assuming you have a Mongoose Connection
object named conn
that's been opened using mongoose.createConnection
, you can access the native mongo Db
object via conn.db
. From there you can call collectionNames
which should provide what you're looking for:
conn.db.collectionNames(function (err, names) {
// names contains an array of objects that contain the collection names
});
您还可以将集合名称作为参数传递给 collectionNames
以将结果过滤为您要查找的内容.
You can also pass a collection name as a parameter to collectionNames
to filter the results to just what you're looking for.
猫鼬 4.x 更新
在 Mongoose 4.x 使用的 MongoDB 本机驱动程序的 2.x 版本中,collectionNames
已被替换为 listCollections
它接受一个过滤器并返回一个游标,所以你可以这样做:
In the 2.x version of the MongoDB native driver that Mongoose 4.x uses, collectionNames
has been replaced by listCollections
which accepts a filter and returns a cursor so you would do this as:
mongoose.connection.db.listCollections({name: 'mycollectionname'})
.next(function(err, collinfo) {
if (collinfo) {
// The collection exists
}
});
这篇关于Node.js - Mongoose - 检查集合是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!