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.