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

时间:2012-11-18 21:37:03

标签: node.js mongodb mongoose

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

我知道如何检查集合是否存在的方式是查询system.namespaces集合。我可以看到3种可行的方法。

  1. 找到一种使用mongoose查询system.namespaces的方法(可能定义与数据库中的模式匹配的模式)。
  2. 从mongoose获取一些底层node-mongodb-native对象并手动执行查询。无论如何,这是我想学习的方法。
  3. 使用node-mongodb-native(或其他一些驱动程序)的单独实例来执行查询
  4. 数字3是最不优雅的,也是我想要避免的,我不想加载驱动程序的另一个实例,也不想在mongoose创建一个连接时创建新的连接。

    写完这篇文章之后我会尝试编号1。我刚检查system.namespaces,架构看起来很简单

    我仍然希望听到一些意见。

    谢谢!

4 个答案:

答案 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
    }
  })
})

'''
resultnullobject

答案 3 :(得分:-8)

在集合列表中查找集合

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