简体   繁体   中英

How to clone a Mongodb database with Mongoose

Is there a way to clone a collection or entire Mongodb database (my databases only have one collection so both options are OK) with Mongoose? I saw that there is a possibility to execute raw Mongo commands with Mongoose. What command can I use to clone an entire collection or db from one db to another?

Thanks in advance.

I had a hard time doing this I don't have any reference.

However, this is how I did on my end.

1, I created another collection within the same

db: mydb
collections: books, oldbooks

2, Since I only know how to connect to one database at a time, I stick to this:

mongoose.connect(process.env.CONN_STR);

3, On your existing collection, in this case, books, we have this code:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var BookSchema = new Schema({
  name: String
})

module.exports = mongoose.model('Book', BookSchema);

4, I created a different Schema for the backup so I can specific the name of the collection:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var ObjectId = Schema.ObjectId;

    var BackupSchema = new Schema({
      name: String
    }, {
      collection: 'oldbooks'
    })

    module.exports = mongoose.model('BackupBook', BackupBookSchema);

NOTICE: that we specified the collection in BackupBook Schema collection: 'oldbooks' . The idea is to replicate the existing schema to the backup schema.

5, Fetch and save each entry in the collection:

 Book.find()
    .exec((err, books) => {
      if(err) throw err
      else {
        books.forEach( (book) => {
          var backup = new BackupBook();

          backup._id = book._id;
          backup.name = book.name;

          backup.save((err, backup) => {
          })
        })
      }
    })

TLDR: Create a different collection as backup. Query each entry of the collection then save to the backup Schema individually. Note, the backup schema must specify the name of the collection.

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