Node.js - Mongoose - 检查集合是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13444876/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:40:03  来源:igfitidea点击:

Node.js - Mongoose - Check if a collection exists

node.jsmongodbmongoose

提问by Juan Campa

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.

我需要使用 mongoose 插入一些数据,但集合的名称是在插入时由用户提供的,所以我首先必须检查集合是否存在。

The way I know how to check if a collection exists is by querying the system.namespacescollection. I can see 3 possible approaches to doing that.

我知道如何检查集合是否存在的方法是查询system.namespaces集合。我可以看到 3 种可能的方法来做到这一点。

  1. Find a way to query system.namespacesusing 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
  1. 找到一种system.namespaces使用 mongoose进行查询的方法(可能定义一个与数据库中的模式相匹配的模式)。
  2. 从 mongoose 获取一些底层 node-mongodb-native 对象并手动执行查询。无论如何,这是我想学习如何做的事情。
  3. 使用 node-mongodb-native(或其他一些驱动程序)的单独实例来执行查询

Number 3is 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.

Number3是最不优雅的,也是我试图避免的,我不想加载驱动程序的另一个实例,也不想在 mongoose 已经创建一个连接时创建新连接。

I'm going to try number 1after writing this. I just checked system.namespacesand the schema looks quite simple

1写完这个我要试试数字。我刚刚检查过system.namespaces,架构看起来很简单

I'd still like to hear some opinions.

我还是想听听大家的意见。

Thanks!

谢谢!

回答by JohnnyHK

Option 2 is probably the cleanest. Assuming you have a Mongoose Connectionobject named connthat's been opened using mongoose.createConnection, you can access the native mongo Dbobject via conn.db. From there you can call collectionNameswhich should provide what you're looking for:

选项 2 可能是最干净的。假设您有一个使用打开的Connection名为Mongoose对象,您可以通过 访问本机 mongo对象。从那里你可以调用它应该提供你正在寻找的东西:connmongoose.createConnectionDbconn.dbcollectionNames

conn.db.collectionNames(function (err, names) {
    // names contains an array of objects that contain the collection names
});

You can also pass a collection name as a parameter to collectionNamesto filter the results to just what you're looking for.

您还可以将集合名称作为参数collectionNames传递给以将结果过滤为您要查找的内容。

Mongoose 4.x Update

猫鼬 4.x 更新

In the 2.x version of the MongoDB native driver that Mongoose 4.x uses, collectionNameshas been replaced by listCollectionswhich accepts a filter and returns a cursor so you would do this as:

在 Mongoose 4.x 使用的 MongoDB 本机驱动程序的 2.x 版本中,collectionNames已被替换为listCollectionswhich 接受过滤器并返回一个游标,因此您可以这样做:

mongoose.connection.db.listCollections({name: 'mycollectionname'})
    .next(function(err, collinfo) {
        if (collinfo) {
            // The collection exists
        }
    });

回答by V. Lipunov

This works for me (mongoose version 5.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();
    });
});

回答by user1947323

Find collection in collection's list

在收藏列表中查找收藏

public function CollectionExists($collectionName)
    {
        $mongo = new Mongo();
        $collectionArr = $mongo->selectDB('yourrec')->listCollections();
        if (in_array($collectionName, $collectionArr)) {
            return true;
        }
        return false;
    }