How to clone a Mongodb database with Mongoose

泪湿孤枕 提交于 2021-02-08 07:56:34

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/56726497/how-to-clone-a-mongodb-database-with-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!