Reputation: 71
I need to copy a MongoDB collection from one database to some other database. I need to create an empty collection if there was no data in the source collection. How to do that in nodejs using mongoose libraray?
Upvotes: 3
Views: 9275
Reputation: 41
MongoDB being a NoSQL database, doesn't enforce a strict schema structure like traditional SQL database. So u don't need to create a schema. Lets consider an example where we need to create a student collection having name, age, weight. So if we just write
db.createCollection("students")
The above line has created an empty collection already. So we don't need to do anything specific to create an empty collection. This is the flexibility provided by NoSQL databases like MongoDB. Then whenever we want to populate the database. We just write
db.students.insertOne({ "name": "Chris","age": 23, "weight": 67});
But if you still want to create a schema you can refer this collection's schema using validation in mongodb.
Thanks!
Upvotes: 1
Reputation: 319
You can use connection.createCollection(). http://mongoosejs.com/docs/api.html#connection_Connection-createCollection
This is how I create an empty collection.
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/test");
const mongod = mongoose.connection;
mongod.once('open', function (){
mongod.db.createCollection("emptyCollection", function(){
console.log("done");
})
})
Upvotes: 0
Reputation: 52000
Probably the most efficient way of copying a collection from a DB to an other is to use mongodump/mongorestore from your shell:
sh$ echo 'db.createCollection("some_collection")' | mongo my_dst_db
sh$ mongodump --db my_src_db --collection some_collection --out=- | \
mongorestore --db my_dst_db --collection some_collection --dir=-
The first command will use mongo
to create the destination collection. This is required given your use case as, from what I've just tested, mongorestore
will not create an empty collection. After that, this is just a dump/restore process.
Please note that mongodump
will accept a --query
parameter in case you need a partial copy of your collection.
Upvotes: 2