简体   繁体   中英

how to create the collection in mongodb without any document using mongoose in nodejs

I have tried to copy collections from first db to second db, collections those having documents are copied from first db to second db, but collections with no documents are not getting copied. when I tried to create new collection with empty document, collection gets created with one document containing id field.But my requirement is to create collection without any document in mongodb using mongoose.How to create empty collection in MongoDb using mongoose library and node.js. here goes the code

var data = db.model('name', 'mymodel',"collectionName"),
   newCollection = new data({});
   newCollection .save(function (err) {});

You can use the native MongoDb driver to create an empty collection.

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/dbName', function(err, db) {
    db.createCollection(collectionName, function(err, collection) {
          db.close();
    })
})

Now you can take this a step further and check if the collection exists. If its does skip creation or else create one.

MongoClient.connect('mongodb://localhost:27017/dbName', function(err, db) {

    db.listCollections().toArray(function(err, collections) {
        var collectionExists = false;
        console.log(JSON.stringify(err,null,1));
        if(!err && collections && collections.length>0){
            _.each(collections,function (co) {
                console.log(JSON.stringify(co.name,null,1));
                if(co.name == collectionName){
                    collectionExists = true;
                }
            })
        }

        if(!collectionExists){
            db.createCollection(collectionName, function(err, collection) {

            })
        }
        db.close();
    });
})

References:

  1. http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#listCollections
  2. http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#createCollection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM