如何使用 Mongoose 克隆 Mongodb 数据库 [英] How to clone a Mongodb database with Mongoose

查看:51
本文介绍了如何使用 Mongoose 克隆 Mongodb 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用 Mongoose 克隆一个集合或整个 Mongodb 数据库(我的数据库只有一个集合,所以两个选项都可以)?我看到可以使用 Mongoose 执行原始的 Mongo 命令.我可以使用什么命令将整个集合或数据库从一个数据库克隆到另一个数据库?

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?

提前致谢.

推荐答案

我很难做到这一点,我没有任何参考.

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

然而,我就是这样做的.

However, this is how I did on my end.

1,我在同一个集合中创建了另一个集合

1, I created another collection within the same

db: mydb
collections: books, oldbooks

2、由于我一次只知道如何连接一个数据库,所以我坚持:

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,在您现有的收藏中,在这种情况下,书籍,我们有以下代码:

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,我为备份创建了一个不同的架构,以便我可以指定集合的​​名称:

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

注意:我们在 BackupBook Schema collection: 'oldbooks' 中指定了集合.这个想法是将现有架构复制到备份架构.

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

5、获取并保存集合中的每个条目:

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:创建一个不同的集合作为备份.查询集合的每个条目,然后单独保存到备份模式.请注意,备份架构必须指定集合的​​名称.

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.

这篇关于如何使用 Mongoose 克隆 Mongodb 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆