27

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.

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. 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 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.

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.

Thanks!

4

4 回答 4

40

选项 2 可能是最干净的。假设您有一个Connection名为 Mongoose 的对象conn,该对象已使用 . 打开mongoose.createConnection,您可以Db通过conn.db. 从那里您可以调用collectionNameswhich 应该提供您正在寻找的内容:

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

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

猫鼬 4.x 更新

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

mongoose.connection.db.listCollections({name: 'mycollectionname'})
    .next(function(err, collinfo) {
        if (collinfo) {
            // The collection exists
        }
    });
于 2012-11-18T22:21:12.317 回答
4

这对我有用(猫鼬版本 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();
    });
});
于 2018-06-22T01:40:22.837 回答
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

于 2020-12-16T17:48:59.450 回答
-7

在收藏列表中查找收藏

public function CollectionExists($collectionName)
    {
        $mongo = new Mongo();
        $collectionArr = $mongo->selectDB('yourrec')->listCollections();
        if (in_array($collectionName, $collectionArr)) {
            return true;
        }
        return false;
    }
于 2013-02-25T09:46:03.743 回答