Node.js-猫鼬-检查集合是否存在 [英] Node.js - Mongoose - Check if a collection exists

查看:92
本文介绍了Node.js-猫鼬-检查集合是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用猫鼬来插入一些数据,但是集合的名称是由用户在插入时提供的,因此我首先必须检查集合是否存在.

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.

  1. 找到一种使用猫鼬查询system.namespaces的方法(也许定义与db中的模式匹配的模式).
  2. 从猫鼬获取一些底层的node-mongodb-native对象并手动执行查询.无论如何,这是我想学习的方法.
  3. 使用node-mongodb-native(或其他驱动程序)的单独实例执行查询
  1. Find a way to query system.namespaces using mongoose (maybe defining a schema that matches the one in the db).
  2. 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.
  3. Using a separate instance of a node-mongodb-native (or some other driver) to perform the query

Number 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可能是最干净的.假设您有一个使用mongoose.createConnection打开的名为conn的Mongoose Connection对象,则可以通过conn.db访问本机mongo 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已由

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-猫鼬-检查集合是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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