Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

mongodb - Node.js - Mongoose - Check if a collection exists

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
});

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

Mongoose 4.x Update

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
        }
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...